Android creation and parsing XML (iii)--detailed sax approach _android

Source: Internet
Author: User
Tags xml attribute stringbuffer

1. Sax overview

Sax is a parser that consumes less memory and has a fast parsing speed. It takes the event startup, does not need to parse the entire document, but according to the content order to see whether a part of the document conforms to the XML syntax, if the corresponding event triggers, the so-called event is the callback method (callback), these methods Defined in ContentHandler, the following are the main methods:

startdocument (): triggers this event when a document is encountered this method can be used to do some preprocessing work, such as: Request Object Resources

enddocument (): triggers this event when the document is closed this method can be used to do some cleanup work, such as: Release the requested object resources

startelement (String NamespaceURI, String LocalName, String qName, Attributes atts): This method is triggered when the start tag is encountered.

endelement (String uri, String localname, String name): This event is triggered when an end tag is encountered, which can be done by calling this method.

charachers (char [] ch, int start, int length): This method is triggered when the XML content is encountered, and the content is accepted with the new String (Ch,start,length).

Sax creates XML, applies the standard XML constructor Javax.xml.transform.sax.TransformerHandler event to create an XML document, and needs to import the following

Javax.xml.transform

    • Javax.xml.transform.sax.SAXTransformerFactory;
    • Javax.xml.transform.sax.TransformerHandler;
    • Javax.xml.transform.Transformer;
    • Javax.xml.transform.TransformerConfigurationException;
    • Javax.xml.transform.TransformerFactoryConfigurationError;
    • Javax.xml.transform.OutputKeys;
    • Javax.xml.transform.stream.StreamResult;
    • Javax.xml.transform.sax.SAXTransformerFactory;

Javax.xml.parsers

    • Javax.xml.parsers.SAXParser;
    • Javax.xml.parsers.SAXParserFactory;
    • Javax.xml.parsers.FactoryConfigurationError;
    • Javax.xml.parsers.ParserConfigurationException;

Org.xml.sax

    • Org.xml.sax.Attributes;
    • Org.xml.sax.SAXException;
    • Org.xml.sax.helpers.AttributesImpl;
    • Org.xml.sax.helpers.DefaultHandler;

Sax creates and parses an effect diagram of XML:

2. Sax Create XML

First, Saxtransformerfactory.newinstance () creates a factory instance factory

Next, Factory.newtransformerhandler () Gets the handler object of the Transformerhandler

Then, create Handler.gettransformer (), Handler.setresult (Result), and startdocument (), startelement, characters, and then through the handler event. EndElement, Enddocument (), etc.

/** Sax method, create XML/Public String saxcreatexml () {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 {saxtransformerfactory factory = (saxtransformerfactory) saxtransformerfactorynewinstance (); 
     
    Transformerhandler handler = Factorynewtransformerhandler ();   Transformer Transformer = Handlergettransformer (); 
    Sets the XML attribute Transformersetoutputproperty (outputkeysindent, "yes"); 
    Transformersetoutputproperty (outputkeysencoding, "utf-8"); 
     
    Transformersetoutputproperty (Outputkeysversion, "0");   Streamresult result = new Streamresult (xmlWriter); 
     
    Save the created XML Handlersetresult (result); 
    Handlerstartdocument (); 
     
    Attributesimpl attr = new Attributesimpl (); ATtrclear (); 
    Attraddattribute ("", "", "Author", "", "Homer"); 
    Attraddattribute ("", "", "date", "", "2012-04-27"); 
     
    Handlerstartelement ("", "", "root", attr); 
    int personslen = Personslength; 
      for (int i=0; i<personslen; i++) {attrclear (); 
       
      Handlerstartelement ("", "", "person", attr); 
      Attrclear (); 
      Handlerstartelement ("", "", "id", attr); 
      String id = persons[i]getid () + ""; 
      Handlercharacters (Idtochararray (), 0, Idlength ()); 
 
      Handlerendelement ("", "", "id"); 
      Attrclear (); 
      Handlerstartelement ("", "", "name", attr); 
      String name = Persons[i]getname (); 
      Handlercharacters (Nametochararray (), 0, Namelength ()); 
 
      Handlerendelement ("", "", "name"); 
      Attrclear (); 
      Handlerstartelement ("", "", "blog", attr); 
      String blog = Persons[i]getblog (); 
      Handlercharacters (Blogtochararray (), 0, Bloglength ()); 
       
      Handlerendelement ("", "", "blog"); HandlErendelement ("", "", "person"); 
    } handlerendelement ("", "", "root"); 
     
  Handlerenddocument (); 
  catch (Transformerfactoryconfigurationerror e) {//Saxtransformerfactorynewinstance eprintstacktrace (); 
  catch (Transformerconfigurationexception e) {//Factorynewtransformerhandler eprintstacktrace (); 
  catch (IllegalArgumentException e) {//Transformersetoutputproperty eprintstacktrace (); 
  catch (Saxexception e) {//Handlerstartdocument eprintstacktrace (); 
  catch (Exception e) {eprintstacktrace (); 
  Savedxml (FileName, xmlwritertostring ()); 
return xmlwritertostring (); 
 }

Run Result:

3. Sax parsing xml

  /** sax mode, parse XML/public String saxresolvexml () {StringWriter xmlWriter = new StringWriter (); 
    InputStream is = ReadXML (fileName); 
      try {saxparserfactory factory = Saxparserfactorynewinstance (); 
       
      SAXParser saxparser = Factorynewsaxparser ();  Personhandler handler = new Personhandler ();          Person Handling Handler Saxparserparse (is, handler); 
      Handler parse XML//Get parsed XML String Xmlheader = Handlergetxmlheader (); 
       
      Xmlwriterappend (Xmlheader); 
      list<person> personslist = Handlergetpersons (); 
      int personslen = Personslistsize (); 
      for (int i=0; i<personslen; i++) {xmlwriterappend (Personslistget (i) toString ()) append ("\ n"); 
    The catch (Factoryconfigurationerror e) {//Saxparserfactorynewinstance eprintstacktrace (); 
    catch (Parserconfigurationexception e) {//Factorynewsaxparser eprintstacktrace (); catch (SaxexceptiOn e) {//Factorynewsaxparser eprintstacktrace (); 
    catch (IllegalArgumentException e) {//Saxparserparse eprintstacktrace (); 
    catch (IOException e) {//Saxparserparse eprintstacktrace (); 
    catch (Exception e) {eprintstacktrace (); 
  return xmlwritertostring (); /** handler Processing class * Private Final class Personhandler extends defaulthandler{private list<person> PE Rsonslist = null; 
    Save person Private person person = null;       Private StringBuffer Xmlheader;     Save XML header information private String tag = null; 
    XML Element/** returns the parsed XML header information */public String Getxmlheader () {return xmlheadertostring (); 
    /** returns an array of parsed person instances */public list<person> getpersons () {return personslist; 
      @Override public void Startdocument () throws saxexception{superstartdocument (); Personslist = new Arraylist<persOn> (); 
    Xmlheader = new StringBuffer (); @Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) th 
      Rows saxexception{superstartelement (URI, LocalName, qName, attributes); 
        if ("Root" equals (LocalName)) {String Attrauthor = attributesgetvalue (0); 
        String attrdate = attributesgetvalue (1); 
        Xmlheaderappend ("root") Append ("\t\t"); 
        Xmlheaderappend (attrauthor) Append ("T"); 
      Xmlheaderappend (attrdate) append ("\ n"); 
      else if (' person equals (localname) ') {person = new person (); 
    tag = LocalName; @Override public void characters (char[] ch, int start, int length) throws Saxexception {Supercha 
      Racters (CH, start, length); 
        if (null!= tag) {String value = new String (CH, start, length); 
        Systemoutprintln ("value =" + value); if ("id" equals (tag)) {Personsetid (new IntegER (value)); 
        else if ("name" Equals (tag)) {Personsetname (value); 
        else if ("blog" Equals (tag)) {Personsetblog (value); @Override public void EndElement (string uri, String localname, String qName) throws Saxe 
        xception {if ("person" equals (QName)) {Personslistadd (person); 
      person = null; 
      tag = null; 
    Superendelement (URI, LocalName, QName); 
      @Override public void Enddocument () throws saxexception{//personslist = NULL; 
    Superenddocument (); 
 } 
  }

Run Result:

4, Person class

See previous 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.

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.