本例以Windows, JDK1.7 为基础,来演示使用Java 采用DOM方式来读取XML文件。

相关

在XML文件的创建上面可以参考:Java XML DOM 创建XML文件

XML文件

读取的文件如下,class.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Class>
<Student id="1">
<name>duliu</name>
<age>26</age>
<performance>99</performance>
</Student>
<Student id="2">
<name>tom</name>
<age>23</age>
<performance>90</performance>
</Student>
</Class>
读取文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.devnp.xml.dom;

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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXML {

public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("D:\\Person-Test\\temp\\class.xml");

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder docBuilder = null;

try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Document doc = null ;

try {
doc = docBuilder.parse(file); //load xml
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

doc.getDocumentElement().normalize(); //格式正常化,防止非正常的换行

String rootName = doc.getDocumentElement().getNodeName() ; //获取根节点名

System.out.println("根节点名 : " + rootName); //

NodeList nList = doc.getElementsByTagName("Student");

for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i); //获取每一个student节点

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("Student id : " + eElement.getAttribute("id"));
System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Age : " + eElement.getElementsByTagName("age").item(0).getTextContent());
System.out.println("Performance : " + eElement.getElementsByTagName("performance").item(0).getTextContent());

}
}
}

}
运行结果
1
2
3
4
5
6
7
8
9
根节点名 : Class
Student id : 1
Name : duliu
Age : 26
Performance : 99
Student id : 2
Name : tom
Age : 23
Performance : 90

注意

在DOM方式对XML解析上,需要加载大量XML到内存,增加开销,导致解析速度没SAX方法快。