The
XML specific file is as follows:
code is as follows |
copy code |
<?xml Version= "1.0" encoding= "GBK"?> <Accounts> <account type= " by0003 "> <code>100001</code> <pass>123</pass> <name> Dick </ name> <money>1000000.00</money> </Account> <account type= " hz0001 "> <code>100002</code> <pass>123</pass> <name> John </ name> <money>1000.00</money> </Account> </accounts> |
The Java XML reading class is as follows
The code is as follows |
Copy Code |
Import java.io.*; Import Javax.xml.parsers.DocumentBuilder; Import Javax.xml.parsers.DocumentBuilderFactory; Import org.w3c.dom.Document; Import org.w3c.dom.Element; Import Org.w3c.dom.Node; Import org.w3c.dom.NodeList; public class Xmljava { public static void Main (String args[]) { Element Element=null; File f =new file ("A.xml"); Documentbuilder Db=null;//documentbuilder cannot be directly instantiated for abstraction (convert an XML file to a DOM file) Documentbuilderfactory Dbf=null; try{
Dbf= documentbuilderfactory.newinstance (); Returns the Documentbuilderfactory object DB =dbf.newdocumentbuilder ()//Return DB object Documentbuilderfatory get return Documentbuildr object Document dt= Db.parse (f); Get a DOM and return it to the Document object element = Dt.getdocumentelement ();//Get a elment root
SYSTEM.OUT.PRINTLN ("root element:" +element.getnodename ()); Get root node NodeList childnodes =element.getchildnodes (); To get the child nodes under the root element
for (int i = 0; i < childnodes.getlength (); i++)//traverse these child nodes { Node Node1 = Childnodes.item (i); Childnodes.item (i); Get the node of each corresponding position I if ("Account". Equals (Node1.getnodename ())) { If the name of the node is account, the account element property type is output System.out.println ("RN found an account.") Zone: " + node1.getattributes (). getNamedItem ("type"). Getnodevalue () + "."); NodeList Nodedetail = Node1.getchildnodes (); Get the node under <Accounts> for int j = 0; J < Nodedetail.getlength (); j + +) {//Traversal <Accounts> node Node detail = Nodedetail.item (j); Get <Accounts> Element each node if ("Code". Equals (Detail.getnodename ())/output code SYSTEM.OUT.PRINTLN ("card number:" + detail.gettextcontent ()); else if ("Pass". Equals (Detail.getnodename ())/output Pass System.out.println ("Password:" + detail.gettextcontent ()); else if ("name". Equals (Detail.getnodename ())/output name System.out.println ("Name:" + detail.gettextcontent ()); else if ("Money". Equals (Detail.getnodename ())/output money System.out.println ("Balance:" + detail.gettextcontent ());
} } } } catch (Exception e) {System.out.println (e);}
} } |