xml文本如下:
<root>
<name>百度</name>
<url>http://www.baidu.com</url>
<address>
<street>中关村</street>
<city>北京</city>
<country>中国</country>
</address>
<links>
<name>Google</name>
<url>http://www.google.com</url>
</links>
<links>
<name>Baidu</name>
<url>http://www.baidu.com</url>
</links>
<links>
<name>SoSo</name>
<url>http://www.SoSo.com</url>
</links>
</root>
示例代码:
String xml = "<root>" +
"<name>百度</name>" +
"<url>http://www.baidu.com</url>" +
"<address>" +
"<street>中关村</street><city>北京</city><country>中国</country>" +
"</address>" +
"<links><name>Google</name><url>http://www.google.com</url></links>" +
"<links><name>Baidu</name><url>http://www.baidu.com</url></links><links>" +
"<name>SoSo</name><url>http://www.SoSo.com</url></links>"+
"</root>";
try {
//取得文档对象
Document doc = (Document) DocumentHelper.parseText(xml);
//取得根节点
Element rootElement = doc.getRootElement();
//取得name节点
Element nameElement = rootElement.element("name");
String name = nameElement.getStringValue();
System.out.println("name:"+name);
//取得url节点
Element urlElement = rootElement.element("url");
String url = urlElement.getStringValue();
System.out.println("url:"+url);
//取得根节点中的address节点
Element addressElement = rootElement.element("address");
//取得address节点中的street节点
Element streetElement = addressElement.element("street");
String street = streetElement.getStringValue();
System.out.println("street:"+street);
//取得address节点中的city节点
Element cityElement = addressElement.element("city");
String city = cityElement.getStringValue();
System.out.println("city:"+city);
//取得address节点中的country节点
Element countryElement = addressElement.element("country");
String country = countryElement.getStringValue();
System.out.println("country:"+country);
//取得根节点中的links集合
List<Element> linksElements = rootElement.elements("links");
for (int i = 0; i < linksElements.size(); i++) {
System.out.println("*************"+i+"************");
String lName = linksElements.get(i).element("name").getStringValue();
System.out.println("lName:"+lName);
String lUrl = linksElements.get(i).element("url").getStringValue();
System.out.println("lUrl:"+lUrl);
}
} catch (DocumentException e) {
e.printStackTrace();
}
运行结果:
name:百度
url:http://www.baidu.com
street:中关村
city:北京
country:中国
*************0************
lName:Google
lUrl:http://www.google.com
*************1************
lName:Baidu
lUrl:http://www.baidu.com
*************2************
lName:SoSo
lUrl:http://www.SoSo.com
其中用到了dom4j.jar这个库,下载地址:http://download.csdn.net/detail/tuu_zed/8810405
原文地址:http://blog.csdn.net/tuu_zed/article/details/46513691