1. Dom,document object Model, the DOM-based XML parser transforms an XML document into a collection of object models (the Doc tree), which allows access to any part of the XML document's data at any time by implementing operations on the XML document data for this model operation.
Doc enforces the use of tree models to access information in XML documents
Very flexible, when the XML document large memory requirements are relatively high, and the structure of the complex Doc Tree traversal is also time-consuming, the machine requirements are relatively high.
Step 1: Get the DOM parser factory (the role of the work is to create a specific parser) documentbuilderfactory dbf = Documentbuilderfactory.newinstance (); System.out.println ("Class name:" + Dbf.getclass (). GetName ()); Step 2: Get the specific DOM parser Documentbuilder db = Dbf.newdocumentbuilder (); System.out.println ("Class name:" + Db.getclass (). GetName ()); Step3: Parse an XML document to obtain the Document object (root node) document document = Db.parse ("Candidate.xml"); NodeList list = document.getElementsByTagName ("person");
2, Sax,simple APIs for XML, provides a sequential access pattern, the way to read and write XML data quickly.
Step1: Get the SAX parser factory instance saxparserfactory factory = Saxparserfactory.newinstance (); Step2: Get SAX Parser instance saxparser parser = Factory.newsaxparser (); Step3: Start parsing parser.parse (new File ("Student.xml"), New MyHandler ())
3, JDOM, an open source project, based on tree structure, using pure Java technology to parse, generate, serialize and manipulate XML documents
ImportJava.io.File; ImportJava.io.FileOutputStream; Importjava.util.List; ImportOrg.jdom.Attribute; Importorg.jdom.Document; Importorg.jdom.Element; ImportOrg.jdom.input.SAXBuilder; ImportOrg.jdom.output.Format; ImportOrg.jdom.output.XMLOutputter; Public classJDomTest2 { Public Static voidMain (string[] args)throwsException {saxbuilder builder=NewSaxbuilder (); Document Doc= Builder.build (NewFile ("Jdom.xml")); Element element=doc.getrootelement (); System.out.println (Element.getname ()); Element Hello= Element.getchild ("Hello"); System.out.println (Hello.gettext ()); List List=hello.getattributes (); for(inti = 0; i < list.size (); i++) {Attribute attr=(Attribute) list.get (i); String Attrname=Attr.getname (); String AttrValue=Attr.getvalue (); System.out.println (Attrname+ "=" +attrValue); } hello.removechild ("World"); Xmloutputter out=NewXmloutputter (Format.getprettyformat (). SetIndent ("")); Out.output (Doc,NewFileOutputStream ("Jdom2.xml")); }
}
4, dom4j
XML parsing in Java (four methods)