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> xx, xx Road, xx County, Sichuan Province, x section xx </ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR> xx xiang xx cun xx zu, xx City, Sichuan province </ADDR>
</VALUE>
</RESULT>
Testing Center
Package test.xml;
/**
* Test four class libraries that read XML. Dom,sax,jdom,dom4j<br>
* Pay attention to the speed is not good comparison, because the first is very disadvantage.
*
*/
public class Testxml {
public static void Main (string[] args) {
Dom parsing
Testxmlbydom.main (NULL);
Sax parsing
Testxmlbysax.main (NULL);
Jdom resolution
Testxmlbyjdom.main (NULL);
DOM4J resolution
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;
/**
* Read XML files using the DOM.
*
*/
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");
Constructing DOM
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Documentbuilder builder = Factory.newdocumentbuilder ();
Parsing files
Document doc = Builder.parse (f);
Directly read the value of the node inside the
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's Address:")
+ Doc.getelementsbytagname ("ADDR"). Item (i). Getfirstchild (). Getnodevalue ());
}
catch (Exception e) {
E.printstacktrace ();
}
System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS");
}
}