xml代碼:
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>鄭州市金水區</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>鄭州市二七區</ADDR>
</VALUE>
</RESULT>
Java代碼:
package com.util;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXmlByDom {
public static void main(String args[]) {
File f = new File("F:\\car.xml");
Dom(f);
}
public static void Dom(File f) {
// Document可以看作是XML在內存中的一個鏡像,那么一旦獲取這個Document 就意味
//可以通過對內存的操作來實現對XML的操作
// 首先第一步獲取XML相關的Document
try {
// 很明顯該類是一個單例,先獲取產生DocumentBuilder工廠
// 的工廠,再通過這個工廠產生一個DocumentBuilder,
// DocumentBuilder就是用來產生Document的
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
// 根節點獲得方法
// Element root=doc.getDocumentElement();
// System.out.println("根節點是"+root.getTagName());
NodeList nl = doc.getElementsByTagName("VALUE");
// 父節點獲得方法
// Node fatherNode=nl.item(0);
// System.out.println("父節點是"+fatherNode.getNodeName());
// NamedNodeMap attributes=fatherNode.getAttributes();
// 遍歷XML
for (int i = 0; i < nl.getLength(); i++) {
System.out.println("車牌號是"
+ doc.getElementsByTagName("NO").item(i)
.getFirstChild().getNodeValue());
System.out.println("車主地址是"
+ doc.getElementsByTagName("ADDR").item(i)
.getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
result:
車牌號是A1234
車主地址是鄭州市金水區
車牌號是B1234
車主地址是鄭州市二七區