Jsp tutorial reading XML class library DOM parsing xml instance tutorial
Xml file:
<? Xml version = "1.0" encoding = "GB2312"?>
<RESULT>
<VALUE>
<NO> A1234 </NO>
<ADDR> No. XX, section X, XX Road, XX Town, XX County, Sichuan Province </ADDR>
</VALUE>
<VALUE>
<NO> B1234 </NO>
<ADDR> XX group, XX village, XX Township, xxx City, Sichuan Province </ADDR>
</VALUE>
</RESULT>
Test Center
Package test. xml;
/**
* Test four types of class libraries that read XML. DOM, SAX, JDOM, DOM4J <br>
* Note that the speed is not good because the first one suffers a lot.
*
*/
Public class TestXML {
Public static void main (String [] args ){
// DOM Parsing
TestXMLByDOM. main (null );
// SAX Parsing
TestXMLBySAX. main (null );
// JDOM Parsing
TestXMLByJDOM. main (null );
// DOM4J Parsing
TestXMLByDOM4J. main (null );
}
}
DOM
Package test. xml;
Import java. io. File;
Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;
Import org. w3c. dom. Document;
Import org. w3c. dom. NodeList;
/**
* Use DOM to read XML files.
*
*/
Public class TestXMLByDOM {
Public static void main (String [] args ){
Long lasting = System. currentTimeMillis ();
System. out. println ("Read By DOM ");
Try {
// Xml file
File f = new File ("text. xml ");
// Construct the dom
DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance ();
DocumentBuilder builder = factory. newDocumentBuilder ();
// Parse the file
Document doc = builder. parse (f );
// Directly read the VALUE of the node
NodeList nl = doc. getElementsByTagName ("VALUE ");
For (int I = 0; I <nl. getLength (); I ++ ){
System. out. print ("license plate number :"
+ Doc. getElementsByTagName ("NO"). item (I). getFirstChild (). getNodeValue ());
System. out. println ("owner address :"
+ Doc. getElementsByTagName ("ADDR"). item (I). getFirstChild (). getNodeValue ());
}
} Catch (Exception e ){
E. printStackTrace ();
}
System. out. println ("Run time:" + (System. currentTimeMillis ()-lasting) + "millisecond ");
}
}