Android creation and parsing XML (v)--detailed dom4j approach _android

Source: Internet
Author: User
Tags xml attribute xpath stringbuffer

1, dom4j overview

DOM4J is a easy to use, open Source library for working with XML, XPath and XSLT on the Java platform using the Java Coll The Ections Framework and with the full support for DOM, SAX and JAXP.

DOM4J Official website: dom4j

dom4j source Download: dom4j download

In this example, the Dom4j.jar package needs to be imported to refer to the DOM4J related class, dom4j source code, and jar package, see this example "source download" or access to dom4j

The ORG.DOM4J package contains not only the builder class Documenthelper, the element that created the XML, but also the parser Saxreader, element that parses the XML, containing the following classes:

org.dom4j

    • Org.dom4j.DocumentHelper;
    • Org.dom4j.Element;
    • Org.dom4j.io.SAXReader;
    • Org.dom4j.io.XMLWriter;
    • Org.dom4j.DocumentException;

Create and parse an effect diagram for XML:

2. DOM4J Create XML

DOM4J, creating XML is mainly used for Org.dom4j.DocumentHelper, Org.dom4j.Document, Org.dom4j.io.OutputFormat, Org.dom4j.io.XMLWriter

First, Documenthelper.createdocument (), create an instance of Org.dom4j.Document doc

Then, through Doc, set the XML attribute doc.setxmlencoding ("Utf-8"), Doc.addelement ("root") root node, and child nodes, etc.

Then, define the XML format and output, new XMLWriter (XMLWriter, OutputFormat)

/** dom4j mode, create XML/Public String dom4jxmlcreate () {StringWriter xmlWriter = new StringWriter ();    person []persons = new person[3]; 
  Create node Person object Persons[0] = new Person (1, "sunboy_2050", "http://blogcsdnnet/sunboy_2050"); 
  PERSONS[1] = new Person (2, "Baidu", "http://wwwbaiducom"); 
   
  PERSONS[2] = new Person (3, "Google", "http://wwwgooglecom"); 
     
    try {orgdom4jdocument doc = documenthelpercreatedocument (); 
     
    Docsetxmlencoding ("Utf-8"); 
    Orgdom4jelement eleroot = docaddelement ("root"); 
    Elerootaddattribute ("Author", "Homer"); 
    Elerootaddattribute ("date", "2012-04-25"); 
     
    Elerootaddcomment ("dom4j test"); 
    int personslen = Personslength;  for (int i=0; i<personslen; i++) {Element Eleperson = elerootaddelement (' person '); 
      Creates a person node that references the class to orgdom4jelement Element Eleid = elepersonaddelement ("id"); 
       
      Eleidaddtext (Persons[i]getid () + ""); Element Elename = ElepersonadDelement ("name"); 
       
      Elenameaddtext (Persons[i]getname ()); 
      Element Eleblog = elepersonaddelement ("blog"); 
    Eleblogaddtext (Persons[i]getblog ());  } Orgdom4jiooutputformat OutputFormat = new Orgdom4jiooutputformat (); 
    Sets the XML output format outputformatsetencoding ("Utf-8"); 
    Outputformatsetindent (FALSE); 
    Outputformatsetnewlines (TRUE); 
     
    Outputformatsettrimtext (TRUE);   Orgdom4jioxmlwriter output = new XMLWriter (XMLWriter, OutputFormat); 
    Save XML Outputwrite (DOC); 
  Outputclose (); 
  catch (Exception e) {eprintstacktrace (); 
  Savedxml (FileName, xmlwritertostring ()); 
return xmlwritertostring (); 
 }

Run Result:

3. DOM4J parsing XML

DOM4J, parsing XML is mainly used for Org.dom4j.io.SAXReader, Org.dom4j.Document, Doc.getrootelement (), Ele.getname (), Ele.gettext (), and so on.

First, create the Saxreader instance reader, read the XML byte Stream Reader.read (IS)

Then, the root root node is obtained by Doc.getrootelement (), and the Eleroot.elementiterator () is obtained by using the iterator to get the sub node of the root level.

Then, the parsed XML content Xmlwriter.append (Xmlheader), Xmlwriter.append (Personslist.get (i). toString ())

Parsing one: Standard parsing (iterator iterations)

/** dom4j mode, parse XML/public String dom4jxmlresolve () {StringWriter xmlWriter = new StringWriter (); 
  InputStream is = ReadXML (fileName); 
    try {saxreader reader = new Saxreader (); 
 
    Orgdom4jdocument doc = Readerread (IS); 
    List<person> personslist = null; 
    person person = null; 
     
     
    StringBuffer Xmlheader = new StringBuffer ();   Element eleroot = Docgetrootelement (); 
    Gets the root root node, the reference class is orgdom4jelement String Attrauthor = Elerootattributevalue ("author"); 
    String attrdate = Elerootattributevalue ("date"); 
    Xmlheaderappend ("root") Append ("\t\t"); 
    Xmlheaderappend (attrauthor) Append ("T"); 
    Xmlheaderappend (attrdate) append ("\ n"); 
     
    Personslist = new arraylist<person> (); 
    Gets the root child node, that is, the person iterator<element> iter = Elerootelementiterator (); for (; Iterhasnext ();) 
       
      {element Eleperson = (Element) Iternext (); if ("Person" Equals (Elepersongetname ())} {person = NEw person (); 
        Gets the person child node, that is, ID, name, blog iterator<element> inneriter = Elepersonelementiterator (); for (; Inneriterhasnext ();) 
           
          {element ele = (Element) Inneriternext (); 
            if ("id" Equals (elegetname ())) {String id = elegettext (); 
          Personsetid (Integerparseint (id)); 
            ' Else if (' Name ' Equals (Elegetname ()) {String name = Elegettext (); 
          Personsetname (name); 
            else if ("blog" Equals (Elegetname ()) {String blog = elegettext (); 
          Personsetblog (blog); 
        } personslistadd (person); 
      person = null; 
    } xmlwriterappend (Xmlheader); 
    int personslen = Personslistsize (); 
    for (int i=0; i<personslen; i++) {xmlwriterappend (Personslistget (i) toString ()); 
  } catch (Documentexception e) {eprintstacktrace (); 
   catch (Exception e) { Eprintstacktrace (); 
return xmlwritertostring (); 
 }

Run Result:

Parsing two: Selective parsing (XPath path)

Dom4j+xpath, selectivity only resolves id,doc.selectnodes ("//root//person//id")

/** dom4j mode, parse XML (Mode II)/public String dom4jxmlresolve2 () {StringWriter xmlWriter = new StringWriter (); 
  InputStream is = ReadXML (fileName); 
    try {orgdom4jiosaxreader reader = new Orgdom4jiosaxreader (); 
 
    Orgdom4jdocument doc = Readerread (IS); 
    List<person> personslist = null; 
    person person = null; 
     
     
    StringBuffer Xmlheader = new StringBuffer ();   Element eleroot = Docgetrootelement (); 
    Gets the root root node, the reference class is orgdom4jelement String Attrauthor = Elerootattributevalue ("author"); 
    String attrdate = Elerootattributevalue ("date"); 
    Xmlheaderappend ("root") Append ("\t\t"); 
    Xmlheaderappend (attrauthor) Append ("T"); 
    Xmlheaderappend (attrdate) append ("\ n"); 
     
    Personslist = new arraylist<person> (); @SuppressWarnings ("unchecked") list<element> idlist = (list<element>) docselectnodes ("//root//person//  ID "); 
    Selective get all ids iterator<element> Iditer = Idlistiterator (); while (idItErhasnext ()) {person = new person (); 
      Element idele = (Element) Iditernext (); 
      String id = idelegettext (); 
       
      Personsetid (Integerparseint (id)); 
    Personslistadd (person); 
    } xmlwriterappend (Xmlheader); 
    int personslen = Personslistsize (); 
    for (int i=0; i<personslen; i++) {xmlwriterappend ("id =") append (Personslistget (i) getId () + "") append ("\ n"); 
  } catch (Documentexception e) {eprintstacktrace (); 
  catch (Exception e) {eprintstacktrace (); 
return xmlwritertostring (); 
 }

Note: When parsing XML with XPath, you need to import jaxen;

Jaxen is a open source XPath library written in Java. It is adaptable to many different object models, including DOM, XOM, dom4j, and JDOM. Is it also possible to write adapters that treat non-xml trees such as compiled Java byte code or Java beans as XML, thus Enabling to query this trees with XPath too.

Run Result:

4, Person class

See previous blog Android Create and parse XML (ii)--dom Way "4, Person class"

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.