XML文件,文件名student.xmljava
<?xml version="1.0" encoding="UTF-8"?>node
<students>
<student id="1001">
<stuno>1001</stuno>
<name>張三</name>
<sex>男</sex>
<grade>Java一班</grade>
</student>
<student id="1002">
<stuno>1002</stuno>
<name>李四</name>
<sex>女</sex>
<grade>Java二班</grade>
</student>
<student id="1003">
<stuno>1003</stuno>
<name>小二</name>
<sex>男</sex>
<grade>Java三班</grade>
</student>
<student id="1004">
<stuno>1004</stuno>
<name>小蠟</name>
<sex>女</sex>
<grade>Java四班</grade>
</student>
</students>dom
DOM解析XML文件 DomDemo.javaui
package ximdomdemo;spa
import java.io.IOException;xml
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;對象
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;get
public class DomDemo {it
public static void main(String[] args) {
// 建立解析器工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 由工廠建立一個DocumentBuilder解析器
try {
DocumentBuilder db = factory.newDocumentBuilder();
// 建立一個Document對象
Document doc = db.parse("src/ximdomdemo/student.xml");
// 獲取全部節點
NodeList nodes = doc.getChildNodes();
// 獲取根節點
Node root = nodes.item(0);
System.out.println(root.getNodeName());
// 獲取根節點的全部子節點
NodeList students = root.getChildNodes();
for (int i = 0; i < students.getLength(); i++) {
// 遍歷得到根節點的子節點
Node student = students.item(i);
// 得到根節點下子節點的全部子節點
NodeList texts = student.getChildNodes();
for (int j = 0; j < texts.getLength(); j++) {
// 遍歷根節點下子節點的子節點,並輸出其文本內容
Node text = texts.item(j);
if (text.getNodeName().equals("stuno")) {
System.out.println("學號:" + text.getTextContent());
} else if (text.getNodeName().equals("name")) {
System.out.println("姓名:" + text.getTextContent());
} else if (text.getNodeName().equals("sex")) {
System.out.println("性別:" + text.getTextContent());
} else if (text.getNodeName().equals("grade")) {
System.out.println("班級:" + text.getTextContent());
}
}io
}
} catch (ParserConfigurationException | SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}