XML文档解主要分为四种解析方式,官方提供的两种分别是:DOM 和 SAX,第三方分别是:JDOM 和 DOM4j
测试用的xml文档:
<?xml version="1.0" encoding="UTF-8"?>
<user>
<uname type="3">zhangsan</uname>
<uname type="2">王麻子</uname>
<uname>lisi</uname>
<pwd>
123456
<abcd>
aaaaaaa
<uname type="3">zhaoliu</uname>
</abcd>
<uname>wangwu</uname>
</pwd>
</user>
使用DOM解析如下:
package com.xmldemo; import java.io.IOException;
import java.io.InputStream; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; public class DomTest { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//创建解析的工厂类
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//创建解析
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//获取user.xml的文件流 并且需要保证 xml放在src的根目录
InputStream is = DomTest.class.getClassLoader().getResourceAsStream("user.xml");
//创建文档对象模型
Document document = documentBuilder.parse(is);
//获取指定节点的集合
NodeList nodeList = document.getElementsByTagName("uname");
//遍历并获取
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
System.out.println(element.getTagName() + "----->" + element.getAttribute("type") + "---->" + element.getTextContent());
} }
}
以下是SAX方式解析:
package com.xmldemo; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; public class SaxTest {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//创建解析器的工厂类
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
//创建解析器
SAXParser saxParser = saxParserFactory.newSAXParser();
//获取xml文件流
InputStream is = SaxTest.class.getClassLoader().getResourceAsStream("user.xml");
//创建自己的处理类
MyHandle myHandle = new MyHandle();
//直接进行解析
saxParser.parse(is, myHandle); for (int i = 0; i < myHandle.list.size(); i++) {
System.out.println("SaxTest.main()" + myHandle.list.get(i));
}
}
} /**
* 对XMl处理的方法
* @author Bjsxt2013
*
*/
class MyHandle extends DefaultHandler { public List<String> list = new ArrayList<String>(); private String elementName = null; @Override
public void characters(char[] ch, int start, int length) throws SAXException {
//System.out.println("MyHandle.characters()" + new String(ch, start, length));
if (elementName != null && "uname".equals(elementName)) {
//System.out.println(new String(ch, start, length));
list.add(new String(ch, start, length));
}
} @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
//System.out.println("MyHandle.endElement()" + qName);
elementName = null;
} @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//System.out.println("MyHandle.startElement()" + qName);
elementName = qName;
} @Override
public void startDocument() throws SAXException {
//System.out.println("MyHandle.startDocument()");
} @Override
public void endDocument() throws SAXException {
//System.out.println("MyHandle.endDocument()");
}
}
以下是JDom方式解析:
package com.xmldemo; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter; /**
* 1.如何动态生成xml文件
* 2.如何解析xml文件
* 3.如何修改xml文件
*
* 如何快速的解析xml文件
* @author Bjsxt2013
*
*/
public class JdomTest { public static void main(String[] args) throws Exception {
String filePath = System.getProperty("user.dir") + "\\src\\create.xml";
//System.out.println(filePath);
//createXml(filePath);
parserXml(filePath);
} /**
* 解析并修改XMl文件
* @param filePath
* @throws JDOMException
* @throws IOException
*/
public static void parserXml(String filePath) throws JDOMException, IOException {
//创建JDom的解析器
SAXBuilder saxBuilder = new SAXBuilder();
//获取XML对象的流
InputStream is = JdomTest.class.getClassLoader().getResourceAsStream("create.xml");
//解析并生成document对象
Document document = saxBuilder.build(is);
//获取根节点
Element rootElement = document.getRootElement();
//修改根节点的属性
rootElement.setAttribute("sno", "9999");
rootElement.setAttribute("type01", "aaaaaaaaaaaaaa");
Attribute type = new Attribute("type", "abcdefg");
rootElement.setAttribute(type); //获取指定的子节点
Element stuName = rootElement.getChild("stuName");
Element abcd = stuName.getChild("abcd");
//获取节点对应的值
//System.out.println("JdomTest.parserXml()" + abcd.getText());
abcd.setText("唐僧");
//The attribute already has an existing parent "student"
//abcd.setAttribute(type); //获取所有的子节点
List<Element> list = rootElement.getChildren();
for (int i = 0; i < list.size(); i++) {
System.out.println("JdomTest.parserXml()" + list.get(i).getName());
}
//创建新的节点
Element score = new Element("score");
score.setText("99");
rootElement.addContent(score);
//再所有的节点之后设置文本内容 不能直接调用setText方法
//rootElement.setText("abcdefghijklmn");
rootElement.addContent("abcdefghij");
//设置写出的格式
Format format = Format.getPrettyFormat();//格式良好的
//Format format = Format.getCompactFormat();//格式紧凑的
format.setEncoding("utf-8");
//将文档对象模型写出到硬盘
XMLOutputter xmlOutputter = new XMLOutputter(format);
xmlOutputter.output(document, new FileOutputStream(filePath));
} /**
* 创建一个XML文件
* @param filePath
* @throws FileNotFoundException
* @throws IOException
*/
public static void createXml(String filePath) throws FileNotFoundException, IOException {
//创建学生节点(根节点)
Element rootElement = new Element("student");
//添加属性
rootElement.setAttribute("sno", "201209888");
//创建姓名节点
Element stuName = new Element("stuName");
//给姓名节点设置值
stuName.setText("柳岩");
//创建年龄节点
Element age = new Element("age");
age.setText("18");
//将节点连起来
rootElement.addContent(stuName);
rootElement.addContent(age); //创建文档对象模型
Document document = new Document(rootElement);
//设置写出的格式
Format format = Format.getPrettyFormat();//格式良好的
//Format format = Format.getCompactFormat();//格式紧凑的
format.setEncoding("utf-8");
//将文档对象模型写出到硬盘
XMLOutputter xmlOutputter = new XMLOutputter(format);
xmlOutputter.output(document, new FileOutputStream(filePath));
}
}