First, obtain the factory instance DocumentBuilderFactory domfac = DocumentBuilderFactory. newInstance () of the DOM parser ();
Then obtain the DOM parser from the DOM factory.
DocumentBuilder dombuilder = domfac. newDocumentBuilder ();
) Converts the XML document to be parsed into an input stream so that the DOM parser can parse it.
InputStream is = new FileInputStream ("test1.xml ");
(4) parse the input stream of the XML Document to obtain a Document
Document doc = dombuilder. parse (is );
(5) Get the root node of the XML document
Element root = doc. getDocumentElement ();
(6) obtain the subnode of the node
NodeList books = root. getChildNodes ();
Copy codeThe Code is as follows: package com. st. demo;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. InputStream;
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 XmlReader {
Public static void main (String [] args ){
XmlReader reader = new XmlReader ();
}
Public XmlReader (){
DocumentBuilderFactory domfac = DocumentBuilderFactory. newInstance ();
Try {
DocumentBuilder domBuilder = domfac. newDocumentBuilder ();
InputStream is = new FileInputStream (new File ("D:/test1.xml "));
Document doc = domBuilder. parse (is );
Element root = doc. getDocumentElement ();
NodeList books = root. getChildNodes ();
If (books! = Null ){
For (int I = 0; I <books. getLength (); I ++ ){
Node book = books. item (I );
If (book. getNodeType () = Node. ELEMENT_NODE ){
// (7) obtain the node Attribute Value
String email = book. getAttributes (). getNamedItem ("email"). getNodeValue ();
System. out. println (email );
// Note that the attributes of a node are also its subnodes. Its Node type is also Node. ELEMENT_NODE
// (8) Round Robin subnode
For (Node node = book. getFirstChild (); node! = Null; node = node. getNextSibling ()){
If (node. getNodeType () = Node. ELEMENT_NODE ){
If (node. getNodeName (). equals ("name ")){
String name = node. getNodeValue ();
String name1 = node. getFirstChild (). getNodeValue ();
System. out. println (name );
System. out. println (name1 );
}
If (node. getNodeName (). equals ("price ")){
String price = node. getFirstChild (). getNodeValue ();
System. out. println (price );
}
}
}
}
}
}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}