Download the necessary jar packages:
Activation.jar
Commons-logging-1.0.4.jar
Dom4j-1.6.1.jar
Jaxen-1.1.1.jar
Jdom-1.0.jar
One, DOM
The parser reads the entire document and constructs a tree structure that resides in memory, using the DOM interface to manipulate the tree structure.
Advantages: The entire document tree in memory, easy to operate, support delete, modify, rearrange and so on a variety of functions, high access efficiency.
Disadvantage: The entire document into memory (including useless nodes), wasting time and space; usage: Once the document is parsed, it needs to be accessed more than once; hardware resources are adequate (memory, CPU)
Package xmlparse;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.Calendar;
Import Java.util.Locale;
Import Java.util.TimeZone;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Transformer;
Import javax.xml.transform.TransformerConfigurationException;
Import javax.xml.transform.TransformerException;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;
Import org.w3c.dom.DOMException;
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; /** * Java-brought DOM parsing xml file * * @author ABC * * */PUBlic class Testdom {public static void main (string[] args) {builxmlbydom ();
Parsexmlbydom ();
/** * Generate XML Information */public static void Builxmlbydom () {Long begintime = System.currenttimemillis ();
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
try {//build document Documentbuilder db = Dbf.newdocumentbuilder ();
Document doc=db.newdocument ();
Element root=doc.createelement ("students");
Root.setattribute ("Class", "class");
Root.setattribute ("Count", "3");
Element stu=doc.createelement ("student");
Element name=doc.createelement ("name");
Name.appendchild (Doc.createtextnode ("Xiao Ming"));
Element age=doc.createelement ("Age");
Age.appendchild (Doc.createtextnode ("10"));
Stu.appendchild (name);
Stu.appendchild (age);
Root.appendchild (Stu);
Stu=doc.createelement ("Student");
Stu.setattribute ("position", "monitor");
Name=doc.createelement ("name");
Name.appendchild (Doc.createtextnode ("Xiao Wang")); Age=doc.createelemENT ("Age");
Age.appendchild (Doc.createtextnode ("11"));
Stu.appendchild (name);
Stu.appendchild (age);
Root.appendchild (Stu);
Stu=doc.createelement ("Student");
Name=doc.createelement ("name");
Name.appendchild (Doc.createtextnode ("The Soldier"));
Age=doc.createelement ("Age");
Age.appendchild (Doc.createtextnode ("12"));
Stu.appendchild (name);
Stu.appendchild (age);
Root.appendchild (Stu);
Doc.appendchild (root);
Encapsulates the transformed document object into a Domsource object Domsource xmlsource=new Domsource (DOC); Transforms a document node into an XML file Transformerfactory transfactory=transformerfactory using the transformer object.
Newinstance ();
Transformer Transformer=transfactory.newtransformer ();
Create result file File=new file ("Students.xml");
FileOutputStream Fos;
FOS = new FileOutputStream (file);
Streamresult result=new Streamresult (FOS);
Transformer.transform (Xmlsource, result);
if (fos!=null) {fos.close (); }}catch (ParserconfiguRationexception e) {e.printstacktrace ();
}catch (transformerconfigurationexception e) {e.printstacktrace ();
}catch (FileNotFoundException e) {e.printstacktrace ();
}catch (transformerexception e) {e.printstacktrace ();
}catch (IOException e) {e.printstacktrace ();
} System.out.println ("Dom generation time (milliseconds)" + (System.currenttimemillis ()-begintime));
/** * Parse XML information */public static void Parsexmlbydom () {Long begintime = System.currenttimemillis ();;
try {documentbuilderfactory dbf=documentbuilderfactory.newinstance ();
Documentbuilder Builder=dbf.newdocumentbuilder ();
File File=new file ("Students.xml");
Document doc=builder.parse (file);
NodeList Students=doc.getfirstchild (). Getchildnodes ();
Node Student=null;
Node Node=null;
for (int i=0,len=students.getlength (); i<len;i++) {Student=students.item (i);
NodeList Childs=student.getchildnodes ();
System.out.println ("First" + (i+1) + "student"); for (int J=0,size=childs.getlenGth (); j<size;j++) {Node=childs.item (j);
if ("Name". Equals (Node.getnodename ())) {System.out.println (Node.getnodename () + "---" +node.gettextcontent ());
} if ("Age". Equals (Node.getnodename ())) {System.out.println (Node.getnodename () + "---" +node.gettextcontent ());
catch (Domexception e) {e.printstacktrace ()}}};
catch (Parserconfigurationexception e) {e.printstacktrace ();
catch (Saxexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
} System.out.println ("Dom parsing time (milliseconds)" + (System.currenttimemillis ()-begintime));
}
}
Second, SAX
Features: 1, edge reading edge parsing, applied to large XML documents
2, only support reading
3. Low access efficiency
4. Sequential access
Package xmlparse;
Import Java.io.File;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
public class Testsaxparse {/** * @param args */public static void main (string[] args) {sax ();
public static void Sax () {Long begintime = System.currenttimemillis ();
File F = new file ("Students.xml");
SAXParserFactory SF = Saxparserfactory.newinstance ();
try {SAXParser sp = Sf.newsaxparser ();
Saxhandler handler = new Saxhandler ();
Sp.parse (F, handler);
catch (Exception e) {e.printstacktrace ();
System.out.println ("Sax parsing time (milliseconds)" + (System.currenttimemillis ()-begintime));
}} Saxhandler.java package xmlparse;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;
Import Java.util.Stack;
public class Saxhandler extends DefaultHandler {Stack tags = null;
@Override public void Startdocument () throws Saxexception {tags=new Stack (); @Override Public VOID enddocument () throws Saxexception {while (!tags.isempty ()) {System.out.println ());
Tags.pop ();
} tags=null; @Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) throws Saxex ception {if ("Students". Equals (QName)) {System.out.println (Attributes.getvalue ("class") + "--number-" +
Attributes.getvalue ("Count")); } tags.push (QName);//pressing Stack} @Override public void EndElement (string uri, String localname, String qName) throws SA xexception {Tags.pop ()//remove stack top element} @Override public void characters (char[] ch, int start, int length) throws Saxe xception {string tag= (String) Tags.peek ()//view the top element of the stack without removing the IF ("Name". Equals (Tag)) {System.out.println ("name===" +new S
Tring (ch,start,length));
} if ("Age". Equals (Tag)) {System.out.println ("age===" +new String (ch,start,length)); }
}
}
Third, JDOM
Jdom
Advantage: ① is a tree-based Java API for processing XML, which loads trees in memory
② has no backward-compatible restrictions and is therefore simpler than DOM
③ fast, less defects
④ Java rules with sax
Disadvantage: ① cannot handle documents that are larger than memory
②jdom represents the XML document Logical model. There is no guarantee that each byte is truly transformed.
③ does not provide any actual model of DTDs and schemas for instance documents.
④ does not support the corresponding traversal of the package with the DOM
Best for: Jdom with the convenience of trees, as well as the Java rules of Sax. Use when balancing is needed
JDOM package xmlparse;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.List;
Import org.jdom.Document;
Import org.jdom.Element;
Import org.jdom.JDOMException;
Import Org.jdom.input.SAXBuilder;
Import Org.jdom.output.XMLOutputter;
public class Testjdom {/** * @param args */public static void main (string[] args) {buildxmlbyjdom ();
Parsexmlbyjdom ();
public static String Buildxmlbyjdom () {document Doc=new document ();
Element root=new Element ("students");
Root.setattribute ("Count", "3");
Root.setattribute ("Class", "class");
Doc.setrootelement (root); Root.addcontent (new Element ("student"). Addcontent (new Element ("name"). SetText ("Xiaoming"). Addcontent (new Element ("age")
). SetText ("10")); Root.addcontent (new Element ("student"). Addcontent (new Element ("name"). SetText ("Xiao Wang"). Addcontent (new Element ("Age "). SetText (" 11 ")); Root.addcontent (new Element ("student"). Addcontent (new Element ("name"). SetText ("Soldier"). Addcontent (new Element ("age")
). SetText ("12"));
Bytearrayoutputstream out=new Bytearrayoutputstream ();
Xmloutputter putter=new Xmloutputter ();
try {putter.output (doc, out);
Putter.output (Doc, New FileOutputStream ("Students.xml"));
catch (FileNotFoundException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
return out.tostring ();
public static void Parsexmlbyjdom () {long begintime=system.currenttimemillis ();
File F=new file ("Students.xml");
Saxbuilder builder=new Saxbuilder ();
try {Document doc=builder.build (new FileInputStream (f));
Element root=doc.getrootelement ();
System.out.println (Root.getattributevalue ("class") + "-Number:--" +root.getattributevalue ("Count"));
List List=root.getchildren ("student");
for (int i=0;i<list.size (); i++) {element ele= (Element) list.get (i); System.out.println ("First" + (i+1) + "student");
System.out.println (Ele.getchildtext ("name") + "---" +ele.getchildtext ("Age"));
} catch (FileNotFoundException e) {e.printstacktrace ();
catch (Jdomexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
System.out.println ("Sax parsing time (milliseconds)" + (System.currenttimemillis ()-begintime)); }
}
Four, dom4j
Dom4j is a very, very good Java XML API with excellent performance, powerful features and extreme ease of use, and it is also an open-source software. Now you can see that more and more Java software is using dom4j to read and write XML, and it is particularly worth mentioning that even Sun's JAXM is using DOM4J.
DOM4J package xmlparse;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileWriter;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import Java.util.Iterator;
Import java.util.List;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.Node;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;
public class Testdom4j {/** * @param args */public static void main (string[] args) {buildxmlbydom4j ();
PASERXMLBYDOM4J ();
public static void Buildxmlbydom4j () {Document doc=documenthelper.createdocument ();
Doc.setxmlencoding ("UTF-8");
Element root=doc.addelement ("students");
Root.addattribute ("Class", "Class"). AddAttribute ("Count", "3");
Element student=root.addelement ("student");
Student.addelement ("name"). SetText ("Xiaoming"); Student.addelement ("Age"). SetText ("10 ");
Student=root.addelement ("Student"). AddAttribute ("position", "monitor");
Student.addelement ("name"). SetText ("Xiao Wang");
Student.addelement ("Age"). SetText ("11");
Student=root.addelement ("Student");
Student.addelement ("name"). SetText ("the Soldier");
Student.addelement ("Age"). SetText ("12");
String Xmlstr=doc.asxml ();
try {OutputFormat format=outputformat.createprettyprint ();
XMLWriter writer=new XMLWriter (New FileWriter ("Students.xml"), format);
Writer.setescapetext (FALSE);
Writer.write (XMLSTR);
Writer.close ();
catch (Unsupportedencodingexception e) {e.printstacktrace ();
catch (FileNotFoundException e) {e.printstacktrace ();
}catch (IOException e) {e.printstacktrace ();
public static void Paserxmlbydom4j () {long begintime=system.currenttimemillis ();
Saxreader reader=new Saxreader ();
try {Document Doc=reader.read (new FileInputStream ("Students.xml"));
Element root=doc.getrootelement (); System.out.pRintln (Root.attributevalue ("class") + "--number--" +root.attributevalue ("count"); /* list<node> list=root.selectnodes ("student");/need to introduce Jaxen-1.1.1.jar for (int i=0,len=list.size (); i<len;i+
+) {node node= (node) list.get (i); System.out.println (Node.selectsinglenode ("name"). GetText () + "---" +node.selectsinglenode ("Age"). GetStringValue ()
);
}*/iterator It=root.elementiterator ();
Element Ele;
while (It.hasnext ()) {ele= (Element) it.next ();
System.out.println (Ele.selectsinglenode ("name"). GetText () + "---" +ele.selectsinglenode ("Age"). GetText ());
System.out.println (Ele.elementtext ("name") + "---" +ele.elementtext ("Age"));
} catch (FileNotFoundException e) {e.printstacktrace ();
catch (Documentexception e) {e.printstacktrace ();
System.out.println ("Sax parsing time (milliseconds)" + (System.currenttimemillis ()-begintime)); }
}