It turns out everything is a routine.
Using the DOM to parse XML document steps
1. Create parser Factory Object Documentbuildfactory Object
2. Create parser object by parser factory object, i.e. Documentbuilder object
3. Parsing the specified XML file by the parser object, building the corresponding DOM tree, creating the Document object, generating a Document object
4. Querying the DOM tree node with the Document object as the starting point
5, use the getElementsByTagName method of document to get the element name, generate a NodeList collection,
6. Iterating through the collection
The instance code is as follows:
Importjava.io.IOException;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importjavax.xml.parsers.ParserConfigurationException;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList;Importorg.xml.sax.SAXException;/** Parse Phones.xml file*/ Public classParsexml { Public Static voidMain (string[] arg) {//1. Create parser Factory Object Documentbuildfactory objectDocumentbuilderfactory dbf=documentbuilderfactory.newinstance (); Documentbuilder DB=NULL; Document Dom=NULL; Try { //2. Create parser object by parser factory object, i.e. Documentbuilder objectdb=Dbf.newdocumentbuilder (); //3. Parsing the specified XML file by the parser object, building the corresponding DOM tree, creating the Document object, generating a Document objectDom=db.parse ("Phones.xml"); //4. Querying the DOM tree node with the Document object as the starting point//get all the brand node information, is a collection /** getElementsByTagName (String tagname) returns the NodeList of all the Element contained in the document and with the given tag name in document order. */NodeList brandlist=dom.getelementsbytagname ("Brand"); //Traverse all Brand for(intI=0;i<brandlist.getlength (); i++) {Node brand=Brandlist.item (i); //go to element to get the element value of brandElement brandelement=(Element) brand; String brandname=brandelement.getattribute ("name"); System.out.println (brandname); //Find TypeNodeList typelist=dom.getelementsbytagname ("Type"); for(intJ=0;j<typelist.getlength (); j + +) {Node Typenode=Typelist.item (j); Element TypeName=(Element) Typenode; String Typen=typename.getattribute ("name"); System.out.println ("\ T" +Typen); } } } Catch(parserconfigurationexception e) {e.printstacktrace (); } Catch(saxexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{System.out.println ("End of resolution"); } }}
Java reads XML data (parsing) using the DOM