Parsing XML in the form of sax in Android

Source: Internet
Author: User

Each application that accesses the network has its own server, and we can either submit data to the server or fetch the data from the server. So, what format does this data transmit on the network? In general, we will transmit some formatted data on the network, which has certain structure and semantics. When the other party receives the data message, it can parse it according to the same structure specification, thus obtaining the desired part of the content.

The most common formats for transmitting data over a network are two, XML and JSON. Below, we describe parsing XML by means of sax.

First, prepare a piece of data in XML format. Get_data.xml

1 <Apps>    2     <app>3         <ID></ID>4         <name>Google Maps</name>5         <version>1.0</version>6     </app>7     <app>8         <ID>2</ID>9         <name>Chrome</name>Ten         <version>2.1</version> One     </app> A     <app> -         <ID>3</ID> -         <name>Google Play</name> the         <version>2.3</version> -     </app> - </Apps>

We built the server URL: http://10.0.105.36/get_data.xml

The following is the httpurlconnection way to get the contents of the server, the code is as follows

Private voidsendrequestwithhttpurlconnection () {//turn on threads to send network requests        NewThread (NewRunnable () {@Override Public voidrun () {httpurlconnection connection=NULL; Try{URL URL=NewURL ("Http://10.0.105.36/get_data.xml"); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); //Get input streamInputStream in=Connection.getinputstream (); //read to the fetched streamBufferedReader br=NewBufferedReader (NewInputStreamReader (in)); StringBuilder Response=NewStringBuilder ();                    String Line;  while((Line=br.readline ())! =NULL) {response.append (line); } Parsexmlwithsax (response.tostring ());//This is called the Parsexmlwithsax () method in the following                 }Catch(Exception e) {e.printstacktrace (); }finally {                    if(connection!=NULL) {connection.disconnect ();    }}}). Start (); }

In general, we will create a new class ContentHandler inherits from DefaultHandler, and overrides the five methods of the parent class, as follows:

  

 Packagecom.example.NetTest21;ImportAndroid.util.Log;Importorg.xml.sax.Attributes;Importorg.xml.sax.SAXException;ImportOrg.xml.sax.helpers.DefaultHandler;/*** Created by Demon on 2015/1/18.*/ Public classContentHandlerextendsDefaultHandler {PrivateString NodeName; PrivateStringBuilder ID; PrivateStringBuilder name; PrivateStringBuilder version; @Override Public voidStartdocument ()throwssaxexception {ID=NewStringBuilder (); Name=NewStringBuilder (); Version=NewStringBuilder (); } @Override Public voidStartelement (String uri, String localname, String qName, Attributes Attributes)throwssaxexception {//record the current node nameNodename=LocalName; } @Override Public voidCharacters (Char[] ch,intStartintLengththrowssaxexception {//determine which StringBuilder object to add content to based on the current node name        if("id". Equals (NodeName))        {id.append (ch,start,length); }Else if("Name". Equals (NodeName))        {name.append (ch, start, length); }Else if("Version". Equals (NodeName))        {version.append (ch, start, length); }} @Override Public voidEndElement (String uri, String localname, String qName)throwssaxexception {if("App". Equals (LocalName)) {LOG.D ("ContentHandler", "ID is" +id.tostring (). Trim ()); LOG.D ("ContentHandler", "name is" +name.tostring (). Trim ()); LOG.D ("ContentHandler", "version is" +version.tostring (). Trim ()); //Finally, empty the StringBuilder .Id.setlength (0); Name.setlength (0); Version.setlength (0); }} @Override Public voidEnddocument ()throwssaxexception {}}

    We first define an StringBuilder object for the ID, name, and version nodes, and initialize them in the Startdocument () method. The Startelement () method is called whenever a node is started to be parsed. Where the localname parameter records the name of the current node , we record it. The characters () method is then called when parsing the specific contents of the node, and we judge by the current node name and add the parsed content to which StringBuilder object. Finally, in the EndElement () method, if the app node has been resolved, the content of ID name and version will be printed. note that the current ID, name, and version may include carriage Returns or line feeds, so we need to call the trim () method before printing, and then erase the contents of the StringBuilder after printing. Otherwise, it will affect the next read of the content.

Next, create a new Parsexmlwithsax (String xmlData) method to parse the data.

 Private voidParsexmlwithsax (String xmlData) {Try{SAXParserFactory Factory=saxparserfactory.newinstance (); XMLReader XMLReader=Factory.newsaxparser (). Getxmlreader (); ContentHandler Handler=NewContentHandler (); //to set an instance of ContentHandler to XmlReaderXmlreader.setcontenthandler (handler); //Start parsingXmlreader.parse (NewInputSource (NewStringReader (xmlData)); }Catch(Exception e) {e.printstacktrace (); }    }

The Parsexmlwithsax () method first creates a Saxparsefactory object, then gets to the XmlReader object, and then sets the instance of ContentHandler we wrote to XmlReader, Finally, the parse () method is called to begin parsing.

---------------------------------------------------------------------------

---------------------------------------------------------------------------

The article comes from the Guo Lin "the first line of code", reproduced please indicate the source.

Parsing XML in the form of sax in Android

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.