DOM 解析

daiwen305發表於2011-11-16

==================
DOMParseXML.java
==================
import java.io.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;


public class DOMParseXML {
public DOMParseXML() {
// 得到DOM解析器的工廠例項
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// 得到DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
// 把要解析的XML文件轉化為輸入流,以便DOM解析器解析它
InputStream is = new FileInputStream("src\\configure.xml");
// 解析XML文件的輸入流,得到一個Document
Document doc = db.parse(is);
// 得到XML文件的根節點
Element root = doc.getDocumentElement();
// 得到節點的子節點
NodeList bookList = root.getChildNodes();
if (bookList != null) {
for (int i = 0; i < bookList.getLength(); i++) {
Node book = bookList.item(i);
if (book.getNodeType() == Node.ELEMENT_NODE) {
String email = book.getAttributes().getNamedItem(
// 取得節點的屬性值
"email").getNodeValue();
System.out.println("Email: " + email);
for (Node node = book.getFirstChild(); node != null; node = node
.getNextSibling()) {
if (node.getNodeName().equals("name")) {
String name = node.getFirstChild()
.getNodeValue();
System.out.println("Name: " + name);


}
if (node.getNodeName().equals("price")) {
String price = node.getFirstChild()
.getNodeValue();
System.out.println("Price: " + price + "\n");


}


}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}


}


public static void main(String[] args) {
new DOMParseXML();


}


}
============================
configure.xml
==========
<?xml version="1.0" encoding="gbk"?>
<books>
<book email="1">
<name>121</name>
<price>55555555</price>
</book>
<book email="2">
<name>212</name>
<price>6666666666</price>
</book>
</books>

相關文章