Android Learning 22 (parsing XML using sax)

Source: Internet
Author: User

The previous blog was using pull to parse the XML file, but it was not our only option, although it was very useful. Sax parsing is also a particularly common method of parsing XML, although its usage is more complex than pull parsing, but it is more explicit in semantics.

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

Package Com.jack.networktest;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;public class MyHandler extends DefaultHandler {@Overridepublic void characters ( char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubsuper.characters (CH, start, length );} @Overridepublic void Enddocument () throws Saxexception {//TODO auto-generated method Stubsuper.enddocument ();} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated met Hod stubsuper.endelement (URI, LocalName, qName);} @Overridepublic void Startdocument () throws Saxexception {//TODO auto-generated method Stubsuper.startdocument ();} @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { TODO auto-generated Method Stubsuper.startelement (URI, LocalName, qName, Attributes);}}


The Startdocument () method is called at the beginning of XML parsing, and the Startelement method is called when it starts parsing a node.
The characters method is called when it gets the contents of the node, and the EndElement method is called when it finishes parsing a junction, and the Enddocument () method is called when the XML parsing is complete. Of these, the three methods of startelement, characters and endelement are parameters, and the data parsed from the XML is passed into these methods as parameters. It is important to note that the characters method may be called more than once when getting the content in the node, and some line breaks are parsed as content, and we need to be in control of the situation in the code.
So let's try to invoke sax parsing in a way that implements the same functionality as the previous blog. Create a new ContentHandler class that inherits from
DefaultHandler, and rewrite the five methods of the parent class as follows:

Package Com.jack.networktest;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;import Android.util.log;public class ContentHandler extends DefaultHandler { Private String nodename;private StringBuilder id;private StringBuilder name;private StringBuilder version;@ overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method stub//s Uper.characters (CH, start, length);//based on the current node name, determine which StringBuilder object to add the content to if ("id". Equals (NodeName)) {id.append (ch, Start,length);//LOG.D ("ContentHandler", "Id.append (ch,start,length)"; +id.tostring (). Trim ());} else if ("name". Equals (NodeName)) {name.append (ch,start,length);} else if ("Version". Equals (NodeName)) {version.append (ch,start,length);}} @Overridepublic void Enddocument () throws Saxexception {//TODO auto-generated method Stub//super.enddocument ();} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO Auto-geNerated method Stub//super.endelement (URI, LocalName, QName), 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 the StringBuilder will be emptied out id.setlength (0); Name.setlength (0); version.setlength (0);//LOG.D ("ContentHandler", "app App app =" +nodename);} LOG.D ("ContentHandler", "endElement =" +localname);} @Overridepublic void Startdocument () throws Saxexception {//TODO auto-generated method Stub//super.startdocument (); id= New StringBuilder (); name=new StringBuilder (); version=new StringBuilder (); @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { TODO auto-generated Method Stub//super.startelement (URI, LocalName, qName, attributes); nodeName = localname;// Record the current node name//LOG.D ("ContentHandler", "Startelement localname=" +localname);}}

We first defined a StringBuilder object for the Id,name and version nodes, and in the Startdocument method
They are initialized. Whenever a node is parsed, the Startelement method gets called, where the LocalName parameter records the current
The name of the knot, and here we record it. Then the characters method is called when parsing the specific contents of the node, and we will judge by the current node name and add the parsed content to which StringBuilder object. Finally, in the EndElement method to judge, if the app node has been resolved, print out the contents of Id,name and version. It is important to note that both Id,name and version may include carriage Returns or newline characters, so we need to call the trim () method before we print, and then erase the contents of StringBuilder after printing. Otherwise, it will affect the next read of the content.
The next task is to modify the code in the mainactivity as follows:

Package Com.jack.networktest;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream; Import Java.io.inputstreamreader;import Java.io.stringreader;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Javax.xml.parsers.saxparserfactory;import Org.apache.http.httpentity;import Org.apache.http.httphost;import Org.apache.http.httprequest;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.responsehandler;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httpurirequest;import Org.apache.http.conn.clientconnectionmanager;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.params.httpparams;import Org.apache.http.protocol.httpcontext;import Org.apache.http.util.entityutils;import Org.xml.sax.inputsource;import Org.xml.sax.xmlreader;import Org.xmlpull.v1.XmlPullparser;import Org.xmlpull.v1.xmlpullparserfactory;import Android.annotation.suppresslint;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.util.log;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.textview;public class Mainactivity extends Activity implements Onclicklistener{public static final int show_response=0;private Button sendrequest=null;private TextView responsetext= Null;private Handler handler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated Method Stubsuper.handlemessage (msg); switch (msg.what) {case show_response:string response= (String) msg.obj;// The UI operation is performed here, the results are displayed on the interface Responsetext.settext (response); break;default:break;}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); sendrequest= (Button) finDviewbyid (r.id.send_request); responsetext= (TextView) Findviewbyid (R.id.response_text); Sendrequest.setonclicklistener (this);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubif (V.getid () ==r.id.send_request) {// Sendrequestwithhttpurlconnection (); Sendrequestwithhttpclient ();}} private void Sendrequestwithhttpurlconnection () {///Open thread initiating network request new Thread (new Runnable () {@Overridepublic void Run () {// TODO auto-generated method stubhttpurlconnection connection=null;try {URL url=new url ("http://www.baidu.com"); Connection = (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream In=connection.getinputstream (); /down face gets to the input stream to read BufferedReader reader=new BufferedReader (New InputStreamReader (in)); StringbuIlder response=new StringBuilder (); String Line;while ((Line=reader.readline ())!=null) {response.append (line);} Message message=new message (); message.what=show_response;//stores the results returned by the server in Message message.obj=response.tostring (); Handler.sendmessage (message);} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Exception e) {e.printstacktrace ();} Finally{if (connection!=null) {connection.disconnect ();}}}). Start ();} private void Sendrequestwithhttpclient () {New Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated Method Stubtry{httpclient httpclient=new defaulthttpclient ();//httpget httpget=new httpget ("http://www.baidu.com") ,///The server address of the specified access is the computer machine, 10.0.2.2 to the simulator is the computer's IP address//8080 for the port number HttpGet httpget=new httpget ("Http://10.0.2.2:8080/get_data.xml"); HttpResponse Httpresponse=httpclient.execute (HttpGet); if (Httpresponse.getstatusline (). GetStatusCode () ==200) {// Both the request and the response were successful httpentity entity=httpresponse.getentity (); String response=entityutils.tostring (entity, "Utf-8");//Call the Parsexmlwithpull method to parse the data returned by the server//parsexmlwithpull (response);// Call the Parsexmlwithsax method to parse the data returned by the server Parsexmlwithsax (response); Message message=new message (); message.what=show_response;//stores the results returned by the server in Message message.obj=response.tostring (); Handler.sendmessage (message);}} catch (Exception e) {e.printstacktrace ();}}}). Start ();} Use pull to parse xmlprivate void Parsexmlwithpull (String xmlData) {//log.d ("mainactivity", "Parsexmlwithpull" (String xmlData ), try{//obtains an instance of Xmlpullparserfactory, and obtains Xmlpullparser object xmlpullparserfactory with this instance factory= Xmlpullparserfactory.newinstance (); Xmlpullparser Xmlpullparser=factory.newpullparser ();// Call Xmlpullparser's SetInput method to set the XML data returned by the server to begin parsing Xmlpullparser.setinput (new StringReader (XmlData)); The current parse event int Eventtype=xmlpullparser.geteventtype () is obtained through the Geteventtype () method; String id= ""; String name= ""; String version= ""; while (eventtype!=xmlpullparser.end_document) {//) the name of the current node is obtained through the GetName () method, if it is found to be equal to ID, name, or version//call the Nexttext () method to get the specific content of the node, and whenever you finish parsing an app node, print out the contents of the string NODENAME=XMLPUllparser.getname ();//LOG.D ("Mainactivity", "" "+eventtype+" Nodename= "+nodename"), switch (eventtype) {//Start parsing a node case XMLPULLPARSER.START_TAG:{IF ("id". Equals (NodeName)) {Id=xmlpullparser.nexttext ();} else if ("name". Equals (NodeName)) {Name=xmlpullparser.nexttext ();} else if ("Version". Equals (NodeName)) {Version=xmlpullparser.nexttext ();} break;} Case Xmlpullparser.end_tag:{if ("Apps". Equals (NodeName)) {log.d ("mainactivity", "ID is" +id); LOG.D ("Mainactivity", "name is" +name); LOG.D ("Mainactivity", "version is" +version); break;} Default:break;} Call the next () method to get to the next parse event Eventtype=xmlpullparser.next ();}} catch (Exception e) {e.printstacktrace ();}} The function for Sax parsing is the private void Parsexmlwithsax (String xmlData) {/* * * * * * * Parsexmlwithsax method first creates a SAXParserFactory object and then gets to the * The XmlReader object, then sets the instance of the ContentHandler we wrote to XmlReader, and finally calls the parse () method to begin parsing. * */try{saxparserfactory factory=saxparserfactory.newinstance (); XMLReader Xmlreader=factory.newsaxparser (). Getxmlreader (); ContentHandler handler=new ContentHandler ();//Will ContentHandlerThe instance is set to XmlReader in Xmlreader.setcontenthandler (handler);//Start parsing xmlreader.parse (New InputSource ( XmlData)));} catch (Exception e) {e.printstacktrace ();}}}

Now run the program again and click the Send Request button to see the printed log as follows:




By the end of the Sax parsing XML, XML also has a way to parse the DOM, and it can be used to parse the XML.



http://blog.csdn.net/j903829182/article/details/42499209


Android Learning 22 (parsing XML using sax)

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.