XMLファイル(文字列)を解析する方法---SAXReader
2267 ワード
SAXReader : TestXML
package *
import java.io.ByteArrayInputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class TestXml {
/**
* @param args
*/
public static void main(String[] args) {
try {
// TODO Auto-generated method stub
// XML
String transMessage = "<?xml version=/"1.0/" encoding=/"GBK/"?><message>"
+ "<body>"
+ "<ticketNotify>"
+ "<ticket id=/"6000012007051000000231/" dealTime=/"20070510165423/" status=/"0000/" message=/" , /"/>"
+ "<ticket id=/"6000012007051000000232/" dealTime=/"20070510165424/" status=/"2012/" message=/" /"/>"
+ "</ticketNotify>" + "</body></message>";
// xml
SAXReader reader = new SAXReader();
//
Document document = null;
//
document = reader.read(new ByteArrayInputStream(transMessage
.getBytes("GBK")));
// xml (message)
Element root = document.getRootElement();
//
Element ticket=null;
Iterator tickets = null;
for (tickets = root.element("body").element("ticketNotify").elementIterator(); tickets.hasNext();) {
ticket = (Element) tickets.next();
System.out.print(ticket.attributeValue("id")+" ");
System.out.print(ticket.attributeValue("dealTime")+" ");
System.out.println(ticket.attributeValue("status"));
}
//Element.asXML , XML
System.out.println(root.element("body").asXML());
} catch (Exception e) {
e.printStackTrace();
}
}
}
:
Document document=new SAXReader.reader(“xml / xxx.xml”);// Document
Element root = document.getRootElement()//
Iterator iterator=root.elementIterator(); //
//List<Element> list = ele.elements("ele"); //
Iterator iterator=Element.elementIterator(); //
:Attribute leaderAttr =Element. attribute(“xxx”);
leaderAttr :leaderAttr.getName();
leaderAttr :leaderAttr.getValue()
:Element.getName();
:Element. getText();