Summary of several ways of Java parsing xml

Source: Internet
Author: User
Tags tagname xml parser
Summary of several ways of Java parsing XML

The first type: DOM.

The full name of the DOM is the Document Object model, also known as the documentation objects. In the application, the DOM-based XML parser converts an XML document into a collection of object models (usually called a dom tree), which is the operation of the object model to implement the XML document data. With the DOM interface, an application can access any part of the data in an XML document at any time, so the mechanism of using the DOM interface is also called a random access mechanism.

The DOM interface provides a way to access XML document information through a hierarchical object model, which forms a tree of nodes based on the XML document structure. Regardless of what type of information is described in an XML document, even if it is a tabulation of data, a list of items, or a document, the model generated by using the DOM is the form of a node tree. In other words, the DOM enforces the use of tree models to access information in an XML document. Since XML is essentially a hierarchical structure, this method of description is quite effective.

The random access provided by the DOM tree gives the application a lot of flexibility to control the content in the entire XML document. However, because the DOM parser converts the entire XML document into a DOM tree in memory, the need for memory is higher when the document is larger or the structure is more complex. Also, traversing a tree with a complex structure is a time-consuming operation. Therefore, the DOM Analyzer's requirements for machine performance are relatively high, and the implementation efficiency is not very ideal. However, because the tree structure of the DOM parser is consistent with the structure of the XML document, and given the convenience of random access, the DOM Analyzer has a wide range of use value.

Import Java.io.File; 
Import Javax.xml.parsers.DocumentBuilder; 
 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import org.w3c.dom.Document; 
Import org.w3c.dom.Element; 
 
Import org.w3c.dom.NodeList; public class DomTest1 {public static void main (string[] args) throws Exception {//Step 1: Get the DOM parser factory (work is 
     
Used to create a specific parser) documentbuilderfactory DBF = Documentbuilderfactory.newinstance (); 
     
    System.out.println ("Class name:" + Dbf.getclass (). GetName ()); 
     
Step 2: Obtain 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 (new File ("Candidate.xml")); 
     
    NodeList list = document.getElementsByTagName ("person"); 
       
      for (int i = 0; i < list.getlength (); i++) {Element element = (Element) list.item (i); String content = Element.getelementsbytagname("NAME"). Item (0). Getfirstchild (). Getnodevalue (); 
       
      System.out.println ("Name:" + content); 
       
      Content = Element.getelementsbytagname ("Address"). Item (0). Getfirstchild (). Getnodevalue (); 
       
      SYSTEM.OUT.PRINTLN ("Address:" + content); 
       
      Content = Element.getelementsbytagname ("TEL"). Item (0). Getfirstchild (). Getnodevalue (); 
       
      SYSTEM.OUT.PRINTLN ("Tel:" + content); 
       
      Content = Element.getelementsbytagname ("FAX"). Item (0). Getfirstchild (). Getnodevalue (); 
       
      System.out.println ("Fax:" + content); 
       
      Content = Element.getelementsbytagname ("EMAIL"). Item (0). Getfirstchild (). Getnodevalue (); 
       
      System.out.println ("email:" + content); 
    System.out.println ("--------------------------------------"); 
 

 } 
  } 
}
Import Java.io.File; 
Import Javax.xml.parsers.DocumentBuilder; 
 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import org.w3c.dom.Attr; 
Import org.w3c.dom.Comment; 
Import org.w3c.dom.Document; 
Import org.w3c.dom.Element; 
Import Org.w3c.dom.NamedNodeMap; 
Import Org.w3c.dom.Node; 
 
Import org.w3c.dom.NodeList; /** * Use recursion to parse any given XML document and output its contents to the command line * @author Zhanglong * * */public class DomTest3 {public static void Mai 
    N (string[] args) throws Exception {documentbuilderfactory dbf = documentbuilderfactory.newinstance (); 
     
    Documentbuilder db = Dbf.newdocumentbuilder (); 
    Document doc = db.parse (new File ("Student.xml")); 
     
    Gets the root element nodes element root = Doc.getdocumentelement (); 
  Parseelement (root); 
     
    private static void Parseelement (element Element) {String tagName = Element.getnodename (); 
     
    NodeList children = Element.getchildnodes (); 
     
    System.out.print ("<" + TagName); Element elementsAll the attributes of the NamedNodeMap object, which need to be judged NamedNodeMap map = element.getattributes ();  
        If the element has property if (null!= map) {for (int i = 0; i < map.getlength (); i++) {//Get every property of the element 
         
        Attr Attr = (Attr) map.item (i); 
        String attrname = Attr.getname (); 
         
        String AttrValue = Attr.getvalue (); 
      System.out.print ("" + Attrname + "=\" "+ AttrValue +" ""); 
     
    } System.out.print (">"); 
      for (int i = 0; i < children.getlength (); i++) {Node node = Children.item (i); 
       
      Gets the type of the node short nodeType = Node.getnodetype (); 
      if (NodeType = = Node.element_node) {//is an element, continue to recursively parseelement ((ELEMENT) Node); 
      else if (NodeType = = Node.text_node) {//Recursive export System.out.print (Node.getnodevalue ()); 
    else if (NodeType = = Node.comment_node) {System.out.print ("<!--");     
        Comment Comment = (Comment) node; 
         
        Comment Content String data = Comment.getdata (); 
         
        System.out.print (data); 
      System.out.print ("-->"); 
  } System.out.print ("</" + TagName + ">"); 
 } 
}


The second type: SAX.

The full name of Sax:sax is simple API for XML, also known as the XML Simplicity application interface. Unlike DOM, the access pattern that sax provides is a sequential pattern, which is a way to read and write XML data quickly. When parsing an XML document using a SAX parser, a series of events are triggered and the appropriate event handlers are activated, and the application accesses the XML document through these event-handler functions, so the Sax interface is also called the event-driven interface.

Import Java.io.File; 
Import Javax.xml.parsers.SAXParser; 
 
Import Javax.xml.parsers.SAXParserFactory; 
Import org.xml.sax.Attributes; 
Import org.xml.sax.SAXException; 
 
Import Org.xml.sax.helpers.DefaultHandler; public class SaxTest1 {public static void main (string[] args) throws Exception {//step1: Get SAX parser Factory instance S 
     
    Axparserfactory factory = Saxparserfactory.newinstance (); 
     
    Step2: Get SAX Parser instance SAXParser parser = Factory.newsaxparser (); 
     
  Step3: Start parsing parser.parse (New File ("Student.xml"), New MyHandler ()); 
    Class MyHandler extends DefaultHandler {@Override public void startdocument () throws Saxexception { 
  System.out.println ("parse began"); 
  @Override public void Enddocument () throws Saxexception {System.out.println ("parse finished"); @Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) t 
  Hrows saxexception{System.out.println ("start element"); 
    @Override public void EndElement (string uri, String localname, String qName) throws Saxexception { 
  System.out.println ("finish element"); 

 } 
}
Import Java.io.File; 
 
Import Java.util.Stack; 
Import Javax.xml.parsers.SAXParser; 
 
Import Javax.xml.parsers.SAXParserFactory; 
Import org.xml.sax.Attributes; 
Import org.xml.sax.SAXException; 
 
Import Org.xml.sax.helpers.DefaultHandler; public class SaxTest2 {public static void main (string[] args) throws Exception {SAXParserFactory factory = S 
     
    Axparserfactory.newinstance (); 
     
    SAXParser parser = Factory.newsaxparser (); 
  Parser.parse (New File ("Student.xml"), New MyHandler2 ()); 
   
  } class MyHandler2 extends DefaultHandler {private stack<string> Stack = new stack<string> (); 
   
  private String name; 
   
  Private String gender; 
   
  Private String age; @Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) throws SAX 
     
    Exception {Stack.push (qName); for (int i = 0; i < attributes.getlength (); i++) {String attrname = Attributes.getQName (i); 
       
      String AttrValue = Attributes.getvalue (i); 
    System.out.println (attrname + "=" + AttrValue); } @Override public void characters (char[] ch, int start, int length) throws Saxexception {S 
     
    Tring tag = Stack.peek (); 
    if ("Name". Equals (tag)) {name = new String (CH, start,length); 
    else if ("Gender". Equals (tag)) {gender = new String (CH, start, length); 
    else if ("Age". Equals (tag)) {old = new String (CH, start, length); 
  @Override public void EndElement (string uri, String localname, String qName) throws Saxexception {Stack.pop ();//indicates that the element has been parsed and needs to be popped from the stack if ("Student". Equals (QName)) {System.out.println ("name:" + Nam 
      e); 
      System.out.println ("Sex:" + gender); 
       
      System.out.println ("Age:" + aged); 
    System.out.println (); 
 } 
     
  } 
}


The third type: JDOM:

Jdom is an open source project that uses pure Java technology to parse, generate, serialize, and manipulate XML documents based on a tree-structured architecture. (http://jdom.org)

Jdom directly for Java programming services. It leverages the many features of the more powerful Java language (method overload, set concepts, etc.) to effectively combine the functionality of Sax and DOM.

Jdom is a new API function that reads, writes, and operates XML in the Java language. These API functions are optimized to the maximum extent of direct, simple, and efficient conditions.

JDOM Create XML

Import Java.io.FileWriter; 
Import Org.jdom.Attribute; 
Import org.jdom.Comment; 
Import org.jdom.Document; 
Import org.jdom.Element; 
Import Org.jdom.output.Format; 
 
Import Org.jdom.output.XMLOutputter; public class JDomTest1 {public static void main (string[] args) throws Exception {Document document = new DOC 
 
    Ument (); 
 
    element root = new Element ("root"); 
 
    Document.addcontent (root); 
 
    Comment Comment = new Comment ("This was my comments"); 
 
    Root.addcontent (comment); 
 
    Element e = new Element ("Hello"); 
 
    E.setattribute ("Sohu", "www.sohu.com"); 
 
    Root.addcontent (e); 
 
    Element e2 = new Element ("World"); 
 
    Attribute attr = new Attribute ("Test", "hehe"); 
 
    E2.setattribute (attr); 
 
    E.addcontent (E2); E2.addcontent (New Element ("AAA"). setattribute ("A", "B"). setattribute ("x", "Y"). setattribute ("GG", "hh"). SetText ( 
 
     
    "Text content")); 
     
    Format format = Format.getprettyformat (); format.seTindent (""); 
     
    Format.setencoding ("GBK"); 
 
    Xmloutputter out = new Xmloutputter (format); 
     
  Out.output (document, New FileWriter ("Jdom.xml")); 

 } 
}

Jdom parsing XML

Import Java.io.File; 
Import Java.io.FileOutputStream; 
 
Import java.util.List; 
Import Org.jdom.Attribute; 
Import org.jdom.Document; 
Import org.jdom.Element; 
Import Org.jdom.input.SAXBuilder; 
Import Org.jdom.output.Format; 
 
Import Org.jdom.output.XMLOutputter; public class JDomTest2 {public static void main (string[] args) throws Exception {Saxbuilder builder = new SA 
     
    Xbuilder (); 
     
    Document doc = builder.build (new File ("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 (int i = 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 = new Xmloutputter (Format.getprettyformat (). SetIndent (""));    
     
  Out.output (Doc, New FileOutputStream ("Jdom2.xml")); 

 } 
}

The Fourth kind: 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.

Import Java.io.FileOutputStream; 
 
Import Java.io.FileWriter; 
Import org.dom4j.Document; 
Import Org.dom4j.DocumentHelper; 
Import org.dom4j.Element; 
Import Org.dom4j.io.OutputFormat; 
 
Import Org.dom4j.io.XMLWriter; 
    public class Test1 {public static void main (string[] args) throws Exception {//Create the document and set the root element node of the document: the first way 
    Document document = Documenthelper.createdocument (); 
    Element root = documenthelper.createelement ("student"); 
 
    Document.setrootelement (root); 
    Create the document and set the root element node of the document: The second way element root = documenthelper.createelement ("student"); 
 
    Document document = Documenthelper.createdocument (root); 
 
    Root.addattribute ("name", "Zhangsan"); 
    Element helloelement = root.addelement ("Hello"); 
 
    Element worldelement = root.addelement ("World"); 
    Helloelement.settext ("Hello"); 
 
    Worldelement.settext ("World"); 
 
    Helloelement.addattribute ("Age", "20"); 
 XMLWriter XMLWriter = new XMLWriter ();   Xmlwriter.write (document); 
     
    OutputFormat format = new OutputFormat ("", true); 
    XMLWriter xmlWriter2 = new XMLWriter (New FileOutputStream ("Student2.xml"), format); 
     
    Xmlwriter2.write (document); 
     
    XMLWriter XmlWriter3 = new XMLWriter (New FileWriter ("Student3.xml"), format); 
    Xmlwriter3.write (document); 
 
  Xmlwriter3.close (); 
 

 } 
}
Import Java.io.File; 
Import Java.util.Iterator; 
 
Import java.util.List; 
Import Javax.xml.parsers.DocumentBuilder; 
 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import org.dom4j.Document; 
Import org.dom4j.Element; 
Import Org.dom4j.io.DOMReader; 
 
Import Org.dom4j.io.SAXReader; public class Test2 {public static void main (string[] args) throws Exception {Saxreader Saxreader = new Saxre 
     
    Ader (); 
     
    Document doc = Saxreader.read (new File ("Student2.xml")); 
     
    Element root = Doc.getrootelement (); 
     
    SYSTEM.OUT.PRINTLN ("root element:" + root.getname ()); 
     
    List childlist = root.elements (); 
     
    System.out.println (Childlist.size ()); 
     
    List childList2 = root.elements ("Hello"); 
     
    System.out.println (Childlist2.size ()); 
     
    Element-i = root.element ("Hello"); 
     
    System.out.println (First.attributevalue ("Age")); 
    for (Iterator iter = Root.elementiterator (); Iter.hasnext ();) {Element e = (Element) iter.next (); 
    System.out.println (E.attributevalue ("Age")); 
     
    } System.out.println ("---------------------------"); 
    Documentbuilderfactory dbf = Documentbuilderfactory.newinstance (); 
    Documentbuilder db = Dbf.newdocumentbuilder (); 
     
    Org.w3c.dom.Document Document = db.parse (New File ("Student2.xml")); 
     
    Domreader Domreader = new Domreader (); 
     
    Convert Jaxp's document to dom4j document document D = Domreader.read (document); 
     
    Element rootelement = D.getrootelement (); 
 
  System.out.println (Rootelement.getname ()); 
 

 } 
}
Import Java.io.FileWriter; 
Import Org.jdom.Attribute; 
Import org.jdom.Document; 
Import org.jdom.Element; 
Import Org.jdom.output.Format; 
 
Import Org.jdom.output.XMLOutputter; public class Test3 {public static void main (string[] args) throws Exception {Document document = new Documen 
 
    T (); 
 
    element root = new Element (contact list). setattribute (New Attribute ("Company", "Group A")); 
     
    Document.addcontent (root); 
     
    Element ContactPerson = new Element ("contact"); 
 
    Root.addcontent (ContactPerson);  
        ContactPerson. Addcontent (new Element ("name"). SetText ("John"). Addcontent (new Element ("Company"). SetText ("a company") 
                . Addcontent (new Element ("Phone"). SetText ("021-55556666"). Addcontent (new Element ("address") 
                . Addcontent (new Element ("Street"). SetText ("5 Street"). Addcontent (new Element ("City"). SetText ("Shanghai") 
 
    . Addcontent (New Element ("province"). SetText ("Shanghai City")); Xmloutputter output = New Xmloutputter (Format.getprettyformat (). SetIndent (""). Setencoding ("GBK"); 
 
  Output.output (document, New FileWriter ("Contact.xml"));  } 
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.