The XML text is as follows:
<root> <name>Baidu</name> <URL>Http://www.baidu.com</URL> <address> <street>Zhongguancun</Street> <City >Beijing</City > <country>China</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>
Example code:
String XML ="<root>"+"<name> Baidu </name>"+"<url>http://www.baidu.com</url>"+"<address>"+"<street> Zhongguancun </street><city> Beijing </city><country> China </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 {//Get Document Object doc = (document) Documenthelper. ParseText(XML);Get root node Element rootelement = doc. Getrootelement();Get name node Element nameelement = rootelement. Element("Name");String name = Nameelement. GetStringValue();System. out. println("Name:"+name);Get URL node Element urlelement = rootelement. Element("url");String URL = urlelement. GetStringValue();System. out. println("URL:"+url);Gets the address node in the root node Element addresselement = rootelement. Element("Address");Get the street node in the address node Element streetelement = addresselement. Element("Street");String Street = Streetelement. GetStringValue();System. out. println("Street:"+street);Gets the city node in the Address node, Element cityelement = addresselement. Element("City");String City = cityelement. GetStringValue();System. out. println("City:"+city);Get the country node in the address node Element countryelement = addresselement. Element("Country");String Country = countryelement. GetStringValue();System. out. println("Country:"+country);Gets the links collection in the root node 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();}
Operation Result:
Name:BaiduURL:http://www. Baidu. comStreet:ZhongguancunCity :BeijingCountry:China *************0************LName:GoogleLurl:http://www. Google. com*************1************LName:BaiduLurl:http://www. Baidu. com*************2************LName:SoSoLurl:http://www. SoSo. com
Which used the Dom4j.jar this library,: http://download.csdn.net/detail/tuu_zed/8810405
Parsing of XML