您的位置:首页 > 其它

Dom4j解析XML文档

2015-07-30 15:49 405 查看
Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

测试文档 students.xml

<?xml version="1.0" encoding="GBK"?>
<students class="一班" count="3">
<student>
<name>小明</name>
<age>10</age>
</student>
<student position="班长">
<name>小汪</name>
<age>11</age>
</student>
<student>
<name>小兵</name>
<age>12</age>
</student>
</students>


创建XMLFile对象,创建SAXReader对象,获取document根节点

public void paserXML(){

try {

/*创建SAXReader读取器,用来读取XML文档*/
SAXReader sax = new SAXReader();
/*创建XMLFile对象*/
File xmlFile = new File("students.xml");

/*通过file对象来读取XML文档*/
Document document = sax.read(xmlFile);
/*获得根节点*/
Element rootele = document.getRootElement();
/*从根节点开始遍历所有节点*/
this.getNodes(rootele);
} catch (DocumentException e) {
System.err.println("文档没有节点...");
}
}


从根节点开始递归遍历所有节点

private void getNodes(Element ele) {
// TODO Auto-generated method stub
System.out.println("------------------------------------------------");

/*当前节点的名称、文本内容和属性值*/
System.out.println("节点名称: " + ele.getName());
if(ele.getTextTrim().isEmpty()){
System.out.println("节点没有内容...");
}else{
System.out.println("节点的内容:" + ele.getTextTrim());
}

/*当前节点的所有属性存放到list中*/
List<Attribute> listAttr = ele.attributes();

/*遍历当前节点的所有属性*/
for(Attribute attr : listAttr){
String name = attr.getName();
String value = attr.getValue();
System.out.println("属性名称: " + name + "  属性值: " + value);
}

/*递归遍历当前节点的所有子节点*/
List<Element> listele = ele.elements();
for(Element e : listele){
/*递归*/
this.getNodes(e);
}
}


解析结果

------------------------------------------------
当前节点名称: students
当前节点没有内容...
属性名称: class     属性值: 一班
属性名称: count     属性值: 3
------------------------------------------------
当前节点名称: student
当前节点没有内容...
------------------------------------------------
当前节点名称: name
当前节点的内容:小明
------------------------------------------------
当前节点名称: age
当前节点的内容:10
------------------------------------------------
当前节点名称: student
当前节点没有内容...
属性名称: position  属性值: 班长
------------------------------------------------
当前节点名称: name
当前节点的内容:小汪
------------------------------------------------
当前节点名称: age
当前节点的内容:11
------------------------------------------------
当前节点名称: student
当前节点没有内容...
------------------------------------------------
当前节点名称: name
当前节点的内容:小兵
------------------------------------------------
当前节点名称: age
当前节点的内容:12


写在后面

dom4j合并了许多超出基本XML文档表示的功能,包括集成的XPath支持、XML Schema支持以及用于大文档或流化文档的基于事件的处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: