DOM解析XML综合例子

1.students.xml
<?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+">");
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值