Here's how to use it:
(1) Get the factory instance of DOM parser
Documentbuilderfactory domfac=documentbuilderfactory.newinstance ();
(2) DOM parser obtained from Dom factory
Documentbuilder Dombuilder=domfac.newdocumentbuilder ();
(3) Convert 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 and get a document
Document Doc=dombuilder.parse (IS);
(5) Get the root node of the XML document
Element root=doc.getdocumentelement ();
(6) Get node's child node
NodeList books=root.getchildnodes ();
Java code
- 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) Get the attribute value of the node
- String email=book.getattributes (). getNamedItem ("email"). Getnodevalue ();
- SYSTEM.OUT.PRINTLN (email);
- Note that the properties of the node are also its child nodes. Its node type is also Node.element_node
- (8) Round-robin nodes
- 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 ();
- }
- }
- }
XML code
- <?xml version= "1.0" encoding= "GB2312" standalone= "no"?>
- <books>
- <book email= "Zhoujunhui">
- <name>rjzjh</name>
- <price>jjjjjj</price>
- </book>
- </books>
Methods for calling XML in Java: Documentbuilderfactory