1.students.xml
2.DomParse.java
<?xml version="1.0" encoding="UTF-8"?>
<学生名册>
<!-- 这是一个注释 -->
<学生 学号="1">
<姓名>张三</姓名>
<性别>男</性别>
<年龄>20</年龄>
<!-- 这是一个注释2 -->
</学生>
<学生 学号="2">
<姓名>李四</姓名>
<性别>女</性别>
<年龄>19</年龄>
</学生>
<学生 学号="3">
<姓名>王五</姓名>
<性别>男</性别>
<年龄>21</年龄>
</学生>
</学生名册>
2.DomParse.java
package com.lijun.xml.dom;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
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;
/**
* 使用递归解析任意的XML文档并输出到命令行上
* @author LIJUN
*
*/
public class DomParse {
public static void main(String[] args) throws Exception {
//获得解析器工厂
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//获得解析器
DocumentBuilder builder=factory.newDocumentBuilder();
//获得根节点
Document document=builder.parse(new File("students.xml"));
//获得根元素节点
Element root=document.getDocumentElement();
parseElement(root);
}
/**
* 解析元素
* @param element 元素
*/
private static void parseElement(Element element){
//获得元素标签名
String tagName=element.getNodeName();
System.out.print("<"+tagName);
//获得元素的子节点
NodeList childNodes=element.getChildNodes();
//获得元素属性
NamedNodeMap attributes=element.getAttributes();
if(null!=attributes){
for(int i=0;i<attributes.getLength();i++){
Attr attr=(Attr)attributes.item(i);
String attrName=attr.getName();
String attrValue=attr.getValue();
System.out.print(" "+attrName+"=\""+attrValue+"\"");
}
}
System.out.print(">");
for(int i=0;i<childNodes.getLength();i++){
Node node=childNodes.item(i);
//获得节点类型
short nodeType=node.getNodeType();
if(nodeType==Node.ELEMENT_NODE){
//是元素,继续递归
parseElement((Element)node);
}else if(nodeType==Node.TEXT_NODE){
//是文本,递归出口
System.out.print(node.getNodeValue());
}else if(nodeType==Node.COMMENT_NODE){
//是注释
System.out.print("<!--");
//获得注释内容
Comment comment=(Comment)node;
String data=comment.getData();
System.out.print(data);
System.out.print("-->");
}
}
System.out.print("</"+tagName+">");
}
}