Sample analysis of XML parsing using dom in Java
- 2020-04-01 01:46:39
- OfStack
Dom is a powerful parsing tool for small documents
Why do you say that? Because it loads the entire XML document into memory, forming a document object tree
It sounds scary in general, but it's a lot easier than Sax to use it to read small points
As for its addition and deletion operations, I am not going to write, I was almost ugly to vomit the code when I read the tutorial
That's why later tools like jdom and dom4j existed...
Without further ado, go straight to the code
Dom parsing example
import java.io.File;
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 the parser factory instance and generate the parser
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Create a document object that needs to be parsed
File f = new File("books.xml");
//Parse the Document and return a Document object, at which point the XML Document is loaded into memory
//Well, let the parsing get a little more intense, and the rest is just getting the data
Document doc = builder.parse(f);
//Gets the document root element
//Why did I do that? Because the document object itself is a tree structure, this is the root
//Of course, you can also go straight to the set of elements and skip this step
Element root = doc.getDocumentElement();
//The root node is found above, and here we begin to get the collection of elements under the root node
NodeList list = root.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
//The item() method finds the node in the collection and transitions down to an Element object
Element n = (Element) list.item(i);
//Gets the property map in the object, extracts it with a for loop, and prints it
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 tangled, 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 results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/20130503192138100.png ">