解析XML的若干方法
解析XML分为dom和sax两种方式,各有一些不同的java实现
一、dom:由W3C定义的接口,将整个XML文档读入内存构建成一个DOM树,再对各个节点进行操作
1)xml解析
@Override
public void parseXml(String filename){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(filename);
Element root = doc.getDocumentElement();
NodeList rootNodes = root.getChildNodes();
System.out.println("root's length="+ rootNodes.getLength());
iterateNodeList(root,rootNodes);
}catch(Exception e){
System.out.println(e);
}
}
private void iterateNodeList(Node node, NodeList nodeList){
System.out.println("=========start:"+node.getNodeName()+"============");
int nodeListLength = nodeList.getLength();
for(int i=0;i<nodeListLength;i++){
Node childNode = nodeList.item(i);
logNodeInfo(childNode,false);
if(childNode.getNodeType()==Node.ELEMENT_NODE){
NodeList childNodeList = childNode.getChildNodes();
iterateNodeList(childNode,childNodeList);
}
}
System.out.println("=========end:"+node.getNodeName()+"============");
}
原始xml文档如下:
<?xml version="1.0" encoding="UTF-8"?>
<house location="USA">
<room type="owner">
<area>
<value>35</value>
<unit>m2</unit>
</area>
</room>
<room type="child">
<area>
<value>25</value>
<unit>m2</unit>
</area>
</room>
<room type="guest">
<area>
<value>25</value>
<unit>m2</unit>
</area>
</room>
</house>
从程序parse后的结果可以看到,node之间是有空的文本节点(Node.TEXT_NODE)分隔的,结构如下:

2)xml修改
public void modifyXml(String filename) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(filename);
Element root = doc.getDocumentElement();
root.setAttribute("price", "380000$");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
File file = new File("./src/house-modify.xml");
if(file.exists()) file.delete();
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
StreamResult streamResult = new StreamResult(out);
transformer.transform(domSource, streamResult);
System.out.println("file's absolute path=" + file.getAbsolutePath());
}catch(Exception e){
System.out.println(e);
}
}