Java: DocumentBuilderFactory call the method that the XML instance
- 2020-04-01 01:38:31
- OfStack
First get: get the factory instance of the DOM parser DocumentBuilderFactory domfac = DocumentBuilderFactory. NewInstance ();
Then get 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 get a Document
Document doc = dombuilder. Parse (is);
(5) get the root node of the XML document
Element root = doc. GetDocumentElement ();
(6) get the child node of the node
NodeList books. = root getChildNodes ();
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 & PI;
String email=book.getAttributes().getNamedItem("email").getNodeValue();
System.out.println(email);
//Note that the attributes of a node are also its children. Its Node type is also node.element_node & NBSP;
//(8) rotary cycle child node & NBSP;
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();
}
}
}