1、为什么使用dom4j解析xml
DOM4J 表现更优秀,具有性能优异、功能强大和极端易用使用
2、所需jar包
dom4j-1.6.1.jar
3、使用方法
package com;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jParseXML {
public static void main(String[] args) throws Exception {
SAXReader sax = new SAXReader();
InputStream is = Dom4jParseXML.class.getClassLoader().getResourceAsStream("com/test.xml");
Document doc = sax.read(is);
Element root = doc.getRootElement();
System.out.print(root.getName()+" ");
List<Attribute> list = root.attributes();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).getName()+":"+list.get(i).getValue());
}
List<Element> elelist = root.elements();
for(int i=0;i<elelist.size();i++){
System.out.print(elelist.get(i).getName()+" ");
List<Attribute> alist = elelist.get(i).attributes();
for(int j=0;j<alist.size();j++)
System.out.println(alist.get(j).getName()+":"+alist.get(j).getValue());
Iterator<Element>it = elelist.get(i).elementIterator();
while(it.hasNext()){
Element ele = it.next();
System.out.println(ele.getName()+":"+ele.getText());
}
}
// Iterator<Element> eleit = root.elementIterator();
// while(eleit.hasNext()){
// Element ele = eleit.next();
// System.out.println(ele.getName()+":"+ele.attributeValue("name"));
// System.out.println(ele.node(1).getStringValue());
// }
}
}
原文地址:http://www.cnblogs.com/Wen-yu-jing/p/3816145.html