Dom is a powerful parsing tool that works with small documents
Why do you say that? Because it will load the entire XML document into memory, forming a Document object tree
It sounds scary, but using it to read a little bit of something is quite handy relative to sax.
As for its additions and deletions, and so on, I do not intend to write, when I read the tutorial I almost was the code to be ugly to vomit
Because of this, only then those jdom and dom4j and other tools exist ...
Not much to say, directly on the code
Dom Parsing example
Copy Code code as follows:
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 a parser factory instance and generate a parser
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Documentbuilder builder = Factory.newdocumentbuilder ();
To create a document object that needs to be resolved
File F = new file ("books.xml");
Parses the document and returns a Documents object, at which time the XML document is loaded into memory
Well, let the parsing come more violently, and the rest is to get the data.
Document doc = Builder.parse (f);
Get Document root element
Why do you ask me? Because the Document object itself is a tree structure, here is the root
Of course, you can also directly find the element collection, omit this step
Element root = Doc.getdocumentelement ();
The root node is found above, where 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++) {
Locate the node in the collection by using the item () method and transition down to the element object
Element n = (Element) list.item (i);
Gets the property map in the object, extracts and prints with the For loop
NamedNodeMap node = n.getattributes ();
for (int x = 0; x < node.getlength (); + + +) {
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: