Dom parsing stores the entire XML file to be parsed in the memory.
XML document to be parsed:
<? XML version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> Lee </Name>
<Age> 30 </age>
</Person>
<Person id = "20">
<Name> Leo </Name>
<Age> 24 </age>
</Person>
</Persons>
Java code parsed using DOM:
Package XML;
Import java. Io. ioexception;
Import javax. xml. parsers. documentbuilder;
Import javax. xml. parsers. documentbuilderfactory;
Import javax. xml. parsers. parserconfigurationexception;
Import org. W3C. Dom. Document;
Import org. W3C. Dom. element;
Import org. W3C. Dom. node;
Import org. W3C. Dom. nodelist;
Import org. xml. Sax. saxexception;
Public class domforxml {
Public static void main (string [] ARGs ){
// Use the documentbuilderfactory factory to create a documentbuilder object
Documentbuilderfactory factory = documentbuilderfactory. newinstance ();
Try {
// Generate documentbuilder
Documentbuilder builder = factory. newdocumentbuilder ();
// After this sentence is called, the XML file is parsed and saved in memory.
Document document = builder. parse ("test. xml ");
// Obtain the root element
Element root = Document. getdocumentelement ();
// Match the node and return the Node Set
Nodelist personnodes = root. getelementsbytagname ("person ");
For (INT I = 0; I <personnodes. getlength (); I ++ ){
// Traverse the Node Set
Element personelement = (element) personnodes. item (I );
// Obtain the attributes on the node
String id = personelement. getattribute ("ID ");
// Output
System. Out. println ("ID:" + id );
// Obtain the subnodes under the node
Nodelist personchilds = personelement. getchildnodes ();
// Traverse sub-nodes
For (Int J = 0; j <personchilds. getlength (); j ++ ){
// Determine whether the current node is an element node
If (personchilds. Item (j). getnodetype () = node. element_node ){
Element childelement = (element) personchilds. Item (j );
// Judge the current node
If (childelement. getnodename (). Equals ("name ")){
// Obtain the value corresponding to the current node
System. Out. println ("name:" + childelement. getfirstchild (). getnodevalue ());
} Else if (childelement. getnodename (). Equals ("Age ")){
System. Out. println ("Age:" + childelement. getfirstchild (). getnodevalue ());
}
}
}
}
} Catch (parserconfigurationexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (saxexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}