DOM is a powerful parsing tool suitable for small documents
Why do you say that? Because it will load the entire xml document into memory to form a document object tree
All in all, it sounds scary, but using it to read small things is quite convenient compared to Sax.
As for its addition and deletion operations, etc., I don’t plan to write it. When I was watching the tutorial, I almost vomited because of the ugly code.
It is precisely because of this that tools such as jdom and dom4j existed later...
Not much to say, just go to the code
Dom parsing example
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
//Create a parser factory instance and generate a parser
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Create the document object that needs to be parsed
File f = new File("books.xml");
//Parse the document and return a Document object. At this time, the xml document has been loaded into memory.
//Okay, let's make the parsing more intense, and the rest is to get the data.
Document doc = builder.parse(f);
//Get the document root element
//You ask me why I do this? Because the document object itself is a tree structure, and this is the root of the tree.
//Of course, you can also find the element collection directly and omit this step
Element root = doc.getDocumentElement();
//The root node was found above, and here we start to obtain the collection of elements under the root node.
NodeList list = root.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
//Find the node in the collection through the item() method, and convert it down to an Element object
Element n = (Element) list.item(i);
//Get the attribute map in the object, use a for loop to extract and print
NamedNodeMap node = n.getAttributes();
for (int x = 0; x < node.getLength(); x++) {
Node nn = node.item(x);
System.out.println(nn.getNodeName() + ": " + nn.getNodeValue());
}
//Print element content, the code is very complicated, almost a fixed format
System.out.println("title: " +n.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
System.out.println("author: " + n.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}
}
Output result: