PackageZaxiang;ImportJava.io.*;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList; Public classXmlreadertest { Public Static voidMain (String args[]) {element element=NULL; //Absolute Road strength can be usedFile f =NewFile ("Config/newfile.xml"); //Documentbuilder cannot be instantiated directly (convert XML file to DOM file)Documentbuilder db =NULL; Documentbuilderfactory DBF=NULL; Try { //returns the Documentbuilderfactory objectDBF =documentbuilderfactory.newinstance (); //returns a DB object using the Documentbuilderfatory object to get the returned Documentbuildr objectdb =Dbf.newdocumentbuilder (); //get a DOM and return it to the Document objectDocument dt =Db.parse (f); //get a elment root elementelement =dt.getdocumentelement (); //Get root nodeSYSTEM.OUT.PRINTLN ("root element:" +element.getnodename ()); //get the child nodes under the root elementNodeList childNodes =element.getchildnodes (); //Traverse these child nodes for(inti = 0; I < childnodes.getlength (); i++) { //get the node for each corresponding position INode Node1 =Childnodes.item (i); if("Account". Equals (Node1.getnodename ())) { //if the name of the node is "account", the Account element property type is outputSystem.out.println ("\ r \ n found an account. Owning area: "+ node1.getattributes (). getNamedItem (" type "). Getnodevalue () +". "); //get the node under <Accounts>NodeList Nodedetail =node1.getchildnodes (); //Traverse <Accounts> under a node for(intj = 0; J < Nodedetail.getlength (); J + +) { //get <Accounts> elements of each nodeNode detail =Nodedetail.item (j); if("Code". Equals (Detail.getnodename ()))//Output CodeSYSTEM.OUT.PRINTLN ("card number:" +detail.gettextcontent ()); Else if("Pass". Equals (Detail.getnodename ()))//Output PassSystem.out.println ("Password:" +detail.gettextcontent ()); Else if("Name". Equals (Detail.getnodename ()))//Output NameSystem.out.println ("Name:" +detail.gettextcontent ()); Else if("Money". Equals (Detail.getnodename ()))//Output MoneySystem.out.println ("Balance:" +detail.gettextcontent ()); } } } } Catch(Exception e) {e.printstacktrace (); } }}
The contents of the XML file processed:
<?XML version= "1.0" encoding= "GBK"?><Accounts> < Accounttype= "Type1"> <Code>100001</Code> <Pass>123</Pass> <name>John doe</name> < Money>1000000.00</ Money> </ Account> < Accounttype= "Type2"> <Code>100002</Code> <Pass>123</Pass> <name>Tom</name> < Money>1000.00</ Money> </ Account></Accounts>
Reading XML methods in Java