码迷,mamicode.com
首页 > 其他好文 > 详细

dom4j解析报文

时间:2015-05-12 20:58:31      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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>

dom4j解析报文

标签:

原文地址:http://www.cnblogs.com/mpxBlog/p/4498362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!