Parsing XML using Android PULL

Source: Internet
Author: User

Today, we will use a small example to learn how to use the PULL parser to parse XML files.

(1) first, put an xml file named beauties. XML in the assets Directory. The file content is as follows:

   
       
            
   
    
Fan Bingbing
   28      
        
            
   
    
Yang Mi
   23      
      
   

Write a Beauty class corresponding to the Node in XML in the src directory. The content of the class is as follows:

Package com. pulltest; public class Beauty {// Beauty name private String name; // Beauty age private String age; public String getName () {return name;} public void setName (String name) {this. name = name;} public String getAge () {return age;} public void setAge (String age) {this. age = age ;}@ Overridepublic String toString () {return "Beauty info [age =" + age + ", name =" + name + "]" ;}}

(2) write an interface IBeautyParser In the src directory. Its content is as follows:

Package com. pulltest; import java. io. inputStream; import java. util. list; public interface IBeautyParser {/*** parse the input stream and obtain the Beauty List * @ param is * @ return * @ throws Exception */public List
 
  
Parse (InputStream is) throws Exception;/***** serialize the Beauty object set, get the XML String * @ param beauties * @ return * @ throws Exception */public String serialize (List
  
   
Beauties) throws Exception ;}
  
 

Write a BeautyParserImpl implementation class of the above interface in the src directory. Its content is as follows, and the code has been commented out in detail:

Package com. pulltest; import java. io. inputStream; import java. util. arrayList; import java. util. list; import org. xmlpull. v1.XmlPullParser; import android. util. xml; public class BeautyParserImpl implements IBeautyParser {@ Overridepublic List
 
  
Parse (InputStream is) throws Exception {List
  
   
MList = null; Beauty beauty = null; // by android. util. xml creates an XmlPullParser instance XmlPullParser xpp = Xml. newPullParser (); // sets the input stream and specifies the encoding method xpp. setInput (is, "UTF-8"); // generate the first event int eventType = xpp. getEventType (); while (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {// determine whether the current event is a document start event case XmlPullParser. START_DOCUMENT: mList = new ArrayList
   
    
(); // Initialize the break of the books set; // determine whether the current event is a Tag Element start event case XmlPullParser. START_TAG: if (xpp. getName (). equals ("beauty") {// determines whether the start tag element is book beauty = new Beauty ();} else if (xpp. getName (). equals ("name") {eventType = xpp. next (); // Let the parser point to the value of the name attribute // get the property value of the name tag, and set the name beauty of beauty. setName (xpp. getText ();} else if (xpp. getName (). equals ("age") {// determines whether the start tag element is book eventType = xpp. next (); // Let the parser point to the value of the age property // get the property value of the age tag, and set the age beauty of beauty. setAge (xpp. getText ();} break; // determines whether the current event is a Tag Element end event case XmlPullParser. END_TAG: if (xpp. getName (). equals ("beauty") {// judge whether the end tag element is book mList. add (beauty); // add the book to the books Collection beauty = null;} break;} // enter the next element and trigger the event eventType = xpp. next () ;}return mList ;}@ Overridepublic String serialize (List
    
     
Beauties) throws Exception {// TODO Auto-generated method stubreturn null ;}}
    
   
  
 

(3) create a layout file pulltest. xml in the layout directory. Its content is as follows:

 
     
  
 

The Activity content in the src directory is as follows:

Package com. pulltest; import java. io. inputStream; import java. util. list; import android. app. activity; import android. OS. bundle; import android. widget. textView; import com. example. pulltest. r; public class PullTestActivity extends Activity {// load the Beauty linked List, whose content is parsed from the XML file to get the private List
 
  
BeautyList; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. pulltest); try {// obtain beauties through the open method of assertmanager. the input stream InputStream of the xml file is = this. getAssets (). open ("beauties. xml "); // initialize the custom implementation class BeautyParserImplBeautyParserImpl pbp = new BeautyParserImpl (); // call the parse () method of pbp to spread the input and parse it, the returned linked list result is assigned to beautyListbeautyList = pbp. parse (is);} catch (Exception e) {e. printStackTrace ();} setupViews ();}/*** display data on the mobile phone interface */private void setupViews () {String result = ""; for (Beauty B: beautyList) {result + = B. toString ();} TextView textView = (TextView) findViewById (R. id. textView); textView. setText (result );}}
 

Right-click and run the android project. The result is as follows:

:

Parsing XML using Android PULL

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.