Java如何使用DOM4j解析XML呢?
下文讲述DOM4j解析XML的方法分享,如下所示:
使用Iterator迭代解析xml
DOM4j简介
dom4j是一个开源库 它用于处理XML、 XPath和XSLT dom4j基于Java平台,使用Java的集合框架 全面集成了DOM,SAX和JAXP例:
使用Iterator迭代解析xml
//测试xml文件
<?xml version="1.0" encoding="UTF-8"?>
<students name="zhangsan">
<hello name="lisi">hello Text1</hello>
<hello name="lisi2">hello Text2</hello>
<hello name="lisi3">hello Text3</hello>
<world name="wangwu">world text1</world>
<world name="wangwu2">world text2</world>
<world >world text3</world>
</students>
/**
* dom4j读取并解析xml
*/
public class Dom4JTest2
{
public static void main(String[] args) throws Exception
{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("test.xml"));
// 获取根元素
Element root = document.getRootElement();
System.out.println("Root: " + root.getName());
// 获取所有子元素
list<Element> childList = root.elements();
System.out.println("total child count: " + childList.size());
// 获取特定名称的子元素
List<Element> childList2 = root.elements("hello");
System.out.println("hello child: " + childList2.size());
// 获取名字为指定名称的第一个子元素
Element firstWorldElement = root.element("world");
// 输出其属性
System.out.println("first World Attr: "
+ firstWorldElement.attribute(0).getName() + "="
+ firstWorldElement.attributeValue("name"));
System.out.println("迭代输出-----------------------");
// 迭代输出
for (Iterator iter = root.elementIterator(); iter.hasNext();)
{
Element e = (Element) iter.next();
System.out.println(e.attributeValue("name"));
}
System.out.println("用DOMReader-----------------------");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// 注意要用完整类名
org.w3c.dom.Document document2 = db.parse(new File("test.xml "));
DOMReader domReader = new DOMReader();
// 将JAXP的Document转换为dom4j的Document
Document document3 = domReader.read(document2);
Element rootElement = document3.getRootElement();
System.out.println("Root: " + rootElement.getName());
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


