Android creation and parsing XML (iv)--Detailed pull approach _android

Source: Internet
Author: User
Tags stringbuffer

1, Pull overview

The Android system is ORG.XMLPULL.V1 to create XML-related packages, which not only provide XmlSerializerfor creating XML, It also provides a pull-mode parser for parsing XML Xmlpullparser

Instead of extracting XML events like Xmlpullparser, XmlSerializer is pushing them into the data flow OutputStream or writer.

XmlSerializer provides a very intuitive API that uses Startdocument to start documents, Enddocument end documents, Starttag start elements, Endtag end elements, text additions, and so on.

Pull to create XML, apply standard XML constructor Org.xmlpull.v1.XmlSerializer to create XML, Org.xmlpull.v1.XmlPullParser to parse XML, need to import the following

Org.xmlpull.v1

    • Org.xmlpull.v1.XmlPullParser;
    • Org.xmlpull.v1.XmlPullParserException;
    • Org.xmlpull.v1.XmlPullParserFactory;
    • Org.xmlpull.v1.XmlSerializer;

Pull Create and parse the XML effect diagram:

2. Pull Create XML

Pull way, creating XML is implemented through the XmlSerializer class

First, we get the instance of creating XML through XmlSerializer XmlSerializer

Next, set the XML properties by xmlSerializer the output xmlserializer.setoutput,xmlserializer.startdocument ("Utf-8", null), and so on

Then, create Startdocument, Starttag, text, Endtag, enddocument, etc. through XmlSerializer

 /** pull mode, create XML/Public String pullxmlcreate () {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 {////Mode one: Use Android to provide utility class Androidutilxml//XmlSerializer XmlSerializer = Xmlnewserializer (); 
      Mode two: Use the factory class Xmlpullparserfactory way Xmlpullparserfactory factory = Xmlpullparserfactorynewinstance (); 
       
      XmlSerializer XmlSerializer = Factorynewserializer ();       Xmlserializersetoutput (XmlWriter); 
Saves the created XML xmlserializersetfeature ("Http://xmlpullorg/v1/doc/featureshtml#indent-output", true);     Xmlserializersetproperty ("Http://xmlpullorg/v1/doc/propertieshtml#serializer-indentation", ""); Set Properties//XMLSERIALIZERSETPRoperty ("Http://xmlpullorg/v1/doc/propertieshtml#serializer-line-separator", "\ n");   Xmlserializerstartdocument ("Utf-8", null); 
      <?xml version= ' 0 ' encoding= ' UTF-8 ' standalone= ' yes '?> xmlserializerstarttag ("", "root"); 
      Xmlserializerattribute ("", "Author", "Homer"); 
       
      Xmlserializerattribute ("", "date", "2012-04-28"); 
      int personslen = Personslength;    for (int i=0; i<personslen; i++) {Xmlserializerstarttag ("", "person"); 
        Create the person node Xmlserializerstarttag ("", "id"); 
        Xmlserializertext (Persons[i]getid () + ""); 
 
        Xmlserializerendtag ("", "id"); 
        Xmlserializerstarttag ("", "name"); 
        Xmlserializertext (Persons[i]getname ()); 
 
        Xmlserializerendtag ("", "name"); 
        Xmlserializerstarttag ("", "blog"); 
        Xmlserializertext (Persons[i]getblog ()); 
         
        Xmlserializerendtag ("", "blog"); 
      Xmlserializerendtag ("", "person"); 
    }   
      Xmlserializerendtag ("", "root"); 
       
    Xmlserializerenddocument (); 
    catch (Xmlpullparserexception e) {//Xmlpullparserfactorynewinstance eprintstacktrace (); 
    catch (IllegalArgumentException e) {//Xmlserializersetoutput eprintstacktrace (); 
    catch (IllegalStateException e) {//Xmlserializersetoutput eprintstacktrace (); 
    catch (IOException e) {//Xmlserializersetoutput eprintstacktrace (); 
    catch (Exception e) {eprintstacktrace (); 
    Savedxml (FileName, xmlwritertostring ()); 
  return xmlwritertostring (); 
 }

Run Result:

3. Pull parsing XML

Pull way, parsing XML is implemented through Xmlpullparser class

First, an instance of parsing XML is obtained through Xmlpullparser xpp

Next, enter Xpp.setinput (IS, "utf-8") through the XPP setting to declare a data structure that defines the XML information (such as: Person array)

Then, through XPP parsing start_document, Start_tag, TEXT, End_tag, end_document, etc.

 /** pull mode, parse XML/public String pullxmlresolve () {StringWriter xmlWriter = new StringWriter (); 
    InputStream is = ReadXML (fileName); 
       
      try {////Mode one: Use Android to provide utility class Androidutilxml//Xmlpullparser xpp = Xmlnewpullparser (); 
      Mode two: Use the factory class Xmlpullparserfactory way Xmlpullparserfactory factory = Xmlpullparserfactorynewinstance (); 
       
      Xmlpullparser xpp = Factorynewpullparser (); 
       
      Xppsetinput (IS, "utf-8");   List<person> personslist = null; 
      Save the person node of the XML with person = NULL;     StringBuffer xmlheader = null;   Save XML Header String ele = null; 
      Element flag int eventtype = Xppgeteventtype (); 
          while (xmlpullparserend_document!= eventtype) {switch (eventtype) {case xmlpullparserstart_document:    Personslist = new arraylist<person> ();       Initialize persons xmlheader = new StringBuffer (); 
      Initialize Xmlheader    Break Case Xmlpullparserstart_tag:if ("root" Equals (Xppgetname ())) {String Attrauthor = Xppgetattributev 
            Alue (0); 
            String attrdate = xppgetattributevalue (1); 
            Xmlheaderappend ("root") Append ("\t\t"); 
            Xmlheaderappend (attrauthor) Append ("T"); 
          Xmlheaderappend (attrdate) append ("\ n");     else if ("Person equals" (Xppgetname ()) {person = new person (); 
          Creates a person instance} else if ("id" Equals (xppgetname ())) {ele = "id"; 
          ' Else if (' Name ' Equals (Xppgetname ()) {ele = ' name '; 
          else if ("blog" Equals (Xppgetname ()) {ele = "blog"; 
          else {ele = null; 
           
        } break; Case xmlpullparsertext:if (null!= ele) {if ("id" equals (ele)) {Personsetid (Integer 
            parseint (Xppgettext ())); else if ("Name" Equals (ele)){Personsetname (Xppgettext ()); 
            else if ("blog" Equals (ele)) {Personsetblog (Xppgettext ()); 
           
        }} break; 
            Case xmlpullparserend_tag:if (' person ' equals (Xppgetname ())) {Personslistadd (person); 
          person = null; 
          } ele = null; 
        Break   } EventType = Xppnext (); 
      Next Event Type} xmlwriterappend (Xmlheader); 
      int personslen = Personslistsize (); 
      for (int i=0; i<personslen; i++) {xmlwriterappend (Personslistget (i) toString ()); 
    The catch (Xmlpullparserexception e) {//Xmlpullparserfactorynewinstance eprintstacktrace (); 
    catch (Exception e) {eprintstacktrace ();     
  return xmlwritertostring (); 
 }

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.