[java]代码库
package com.read.xml;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
public class ReadXml {
public static void readXml(String xml){
InputSource in = new InputSource(new StringReader(xml));
in.setEncoding("UTF-8");
SAXReader reader = new SAXReader();
try {
Document document = reader.read(in);
Element root = document.getRootElement();
List<Element> elements = root.elements();
for(Iterator<Element> it = elements.iterator();it.hasNext();){
Element element = it.next();
System.out.println(element.getName()+" : "+element.getTextTrim());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static String addXml() {
return null;
}
public static void main(String[] args) throws Exception {
String xml= "<?xml version=\"1.0\" encoding=\"GBK\"?>" +
"<xml>" +
"<ToUserName><![CDATA[toUser]]></ToUserName>" +
"<FromUserName><![CDATA[fromUser]]></FromUserName>" +
"<CreateTime>1348831860</CreateTime>" +
"<MsgType><![CDATA[text]]></MsgType>" +
"<Content><![CDATA[this is a test]]></Content>" +
"<MsgId>1234567890123456</MsgId>" +
"</xml>";
readXml(xml);
}
}