<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<学生名册>
<学生 学号="1">
<姓名>张三</姓名>
<!-- haha -->
<性别>男</性别>
<年龄>20</年龄>
</学生>
<学生 学号="2">
<姓名>李四</姓名>
<性别>女</性别>
<年龄>19</年龄>
</学生>
<学生 学号="3">
<姓名>王五</姓名>
<性别>男</性别>
<年龄>21</年龄>
</学生>
</学生名册>
package com.syh.xml.dom;
import java.io.File;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomTest3 {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance() ;
DocumentBuilder db = dbf.newDocumentBuilder() ;
Document doc = db.parse(new File("student.xml")) ;
// System.out.println(doc.getXmlEncoding());
// System.out.println(doc.getXmlVersion());
// System.out.println(doc.getXmlStandalone());
//获得 XML 文档的根元素节点
Element rootEle = doc.getDocumentElement() ;
System.out.println(rootEle.getTagName());
//这里一定要注意一下空格!因为空格也是属于节点的孩子的组成部分。
NodeList list = rootEle.getChildNodes() ;
System.out.println(list.getLength());
for(int i = 0 ; i < list.getLength() ; i ++ ) {
System.out.println(list.item(i).getNodeName());
}
System.out.println("----------------节点的类型和节点值-----------------");
for(int i = 0 ; i < list.getLength() ; i ++) {
Node n = list.item(i) ;
//打印节点的类型和节点值
System.out.println(n.getNodeType() + " : " + n.getNodeValue());
}
System.out.println("----------------打印所有节点的文本(不包括节点的属性!但是包括空白!因为空白也是属于文本的)-----------------");
for(int i = 0 ; i < list.getLength() ; i ++ ) {
Node n = list.item(i) ;
System.out.println(n.getTextContent());
}
System.out.println("-----------------拿到属性----------------");
NodeList nodeList = doc.getElementsByTagName("学生") ;
for(int i = 0 ; i < nodeList.getLength() ; i ++) {
NamedNodeMap nnm = nodeList.item(i).getAttributes() ;
String attrName = nnm.item(0).getNodeName() ;
System.out.print(attrName);
System.out.print(" = ");
String attrValue = nnm.item(0).getNodeValue() ;
System.out.print(attrValue);
System.out.println();
}
}
}
控制台上出现的效果:
学生名册
7
#text
学生
#text
学生
#text
学生
#text
----------------节点的类型和节点值-----------------
3 :
1 : null
3 :
1 : null
3 :
1 : null
3 :
----------------打印所有节点的文本(不包括节点的属性!但是包括空白!因为空白也是属于文本的)-----------------
张三
男
20
李四
女
19
王五
男
21
-----------------拿到属性----------------
学号 = 1
学号 = 2
学号 = 3