Import the jar package first
<?XML version= "1.0" encoding= "UTF-8"?><companys> < CompanyID= "Www.baidu.com"> <name>Baidu</name> <Brand>Paws</Brand> <size>10000</size> </ Company> < CompanyID= "sina.cn"> <name>Sina</name> <Brand>Small Icons</Brand> <size>2000</size> </ Company></companys>
PackageZr.com.util;ImportJava.io.File;ImportJava.util.Iterator;Importjava.util.List;ImportOrg.dom4j.Attribute;Importorg.dom4j.Document;Importorg.dom4j.DocumentException;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader;Importorg.omg.CORBA.portable.ValueBase;/** * * @authorLF **/ Public classTestxml { Public Static voidMain (string[] args) {//Create a Saxreader objectSaxreader reader =NewSaxreader (); //Create Document ObjectDocument document =NULL; //read file (XML file) Try{document= Reader.read (NewFile ("Src/test.xml")); } Catch(documentexception e) {e.printstacktrace (); } //Get the heel root nodeElement element =document.getrootelement (); Testxml.getallcontent (Element); } /*** Recursive *@paramnode*/ Public Static voidgetallcontent (Element node) {//Gets the current node nameSystem.out.println ("--current node:" +node.getname ()); //gets all the property nodes of the current nodelist<attribute> attributes =node.attributes (); //traversing attribute nodes for(Attribute attribute:attributes) {System.err.println ("Property Name:" +attribute.getname () + ", property value:" +Attribute.getvalue ()); } //gets the value of the current nodeString value =Node.gettext (); //if the value of the current node is not empty, the output if(!"". Equals (value)) {System.out.println ("Node Name:" +node.getname () + ", node value" +value); } //Creating IteratorsIterator it =Node.elementiterator (); //Traversing child nodes while(It.hasnext ()) {Element Childnode=(Element) it.next (); //Recursivegetallcontent (Childnode); } }}
Java parsing xml (Dom4j.jar)