Xml解析的四种方法: DOM,SAX,JDOM,DOM4J
?DOM4J:
import java.io.ByteArrayInputStream;import java.util.Iterator;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class XmlDOM4JDemo{ public static void main(String[] args) { StringBuffer sb = new StringBuffer(); sb.append("<?xml version='1.0' encoding='UTF-8'?>").append( "<ChannelReturnRequest>").append("<Body>").append("<Status>") .append("0").append("</Status>").append("<Channelinfo>") .append("<ChannelCode>").append("0001") .append("</ChannelCode>").append("<ValidDate>") .append(20121126).append("</ValidDate>").append("<SerialNum>") .append("111111").append("</SerialNum>").append("<ExpireDate>") .append(11111).append("</ExpireDate>").append("</Channelinfo>") .append("<Channelinfo>").append("<ChannelCode>").append("0002") .append("</ChannelCode>").append("<ValidDate>") .append(19870214).append("</ValidDate>").append("<SerialNum>") .append("111111").append("</SerialNum>").append("<ExpireDate>") .append(11111).append("</ExpireDate>").append("</Channelinfo>") .append("</Body>").append("</ChannelReturnRequest>"); byte[] xmldata = sb.toString().getBytes(); try { SAXReader reader = new SAXReader(); Document doc = reader.read(new ByteArrayInputStream(xmldata)); Element root = doc.getRootElement(); Element body = root.element("Body"); Element foo; for (Iterator i = body.elementIterator("Channelinfo"); i.hasNext();) { foo = (Element) i.next(); System.out.println(foo.elementText("ChannelCode")); System.out.println(foo.elementText("ValidDate")); } } catch (Exception e) { e.printStackTrace(); } }}?