Android Learning 21 (parsing XML with pull)

Source: Internet
Author: User

Parsing XML using Pull

In order to test the data obtained from the Internet, we need to configure a server, I am using tomcat6.0, how to configure Tomcat I will not explain. After configuring the Apache-tomcat-6.0.39\webapps\root path in the next place a file can be accessed through the browser, such as: placed a hello.html file, the browser to access the path is:/http Localhost:8080/hello.html

Now create a new Get_data.xml file in the root directory with the following contents:

<apps>    <app>         <id>1</id> <name>google maps</name> <version>1.0 </version>     </app> <app>         <id>2</id> <name>chrome</name> < version>2.1</version>     </app> <app>         <id>3</id> <name>google Play </name> <version>2.3</version>     </app></apps>


With browser access, the display looks like this:




After the steps above, the preparation is over, so let's get and parse the XML data.

There are many kinds of parsing data in XML format, and the more commonly used are pull and sax parsing, so for simplicity, I'm still on the Networktest project basis
Continue to develop so that the code of the previous network communication section can be reused to focus the work on XML data parsing.
Now that the data in the XML format has been provided, it's time to parse out the part of the data we want to get. To modify the code in Mainactivity:

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 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.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) ; Message message=new message ();message.what=show_response;//stores the results returned by the server in the 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, each time the end of parsing an app node will get the content to print out 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 ();}}}

Detailed operation to see the note, now run the next program, and then click the Send Request button to observe the Logcat print log,:



You can see that the content specified by the XML data has been successfully parsed.

The Android interface looks like this





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



Android Learning 21 (parsing XML with pull)

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.