标签:
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import org.dom4j.io.DOMReader;
public class Dom4jTest {
public static void main(String[] args) throws Exception {
//改成dom4j模式解析
DOMReader domReader=new DOMReader();
//构建w3c中的document对象
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder db=factory.newDocumentBuilder();
//通过文档构造器获取文档对象
File file=new File("src/books.xml");
org.w3c.dom.Document domDocument= db.parse(file);
Document doc=domReader.read(domDocument);
//开始解析doc对象
Element root= doc.getRootElement();
//通过ID获取
Element book1= doc.elementByID("BH10001");
//System.out.println(book1.asXML());
//获取当前节点的第一个子节点
Element book= root.element("book");
//System.out.println(book.asXML());
List list= root.elements();
for (Iterator it = list.iterator(); it.hasNext();) {
Element element = (Element) it.next();
//System.out.println(element.asXML());
}
List list2= root.elements("book");
for (Iterator it = list2.iterator(); it.hasNext();) {
Element element = (Element) it.next();
List list3=element.elements("name");
//System.out.println(((Element)list3.get(0)).asXML());
}
Element book2= (Element)root.elements().get(1);
//System.out.println(book2.asXML());
String id=book2.attribute("id").getText();
//System.out.println(id);
//通过xpath路径语言,查询xml节点
Element xbook2 =(Element)root.selectSingleNode("//book[1]");
//System.out.println(xbook2.asXML());
//Attribute xbook2id =(Attribute)root.selectSingleNode("//book[1]/@id");
Element xbook2id =(Element)root.selectSingleNode("/books/book[2]/name");
System.out.println(xbook2id.getText());
List listx=root.selectNodes("/books/book");
for (Iterator it = listx.iterator(); it.hasNext();) {
Element element = (Element) it.next();
// System.out.println(element.element("name").getText());
}
}
}
报文内容:
<?xml version="1.0" encoding="utf-8"?>
<books>
<book ID="BH10001" id="BH10001" haha="哈哈">
<name>java学习</name>
<price>100</price>
<author>itany</author>
</book>
<book id="BH10002">
<name>xml</name>
<price>200</price>
<author>itany</author>
</book>
<book id="BH10003">
<name>js</name>
<price>300</price>
<author>itany</author>
</book>
<book id="BH10004">
<name>jsp</name>
<price>400</price>
<author>itany</author>
</book>
<book id="BH10005">
<name>mysql</name>
<price>500</price>
<author>itany</author>
</book>
</books>
标签:
原文地址:http://www.cnblogs.com/mpxBlog/p/4498362.html