Parse XML files using sax in Android

Source: Internet
Author: User

1. Write an XML file in the assets File

<? XML version = "1.0" encoding = "UTF-8"?> <Persons> <person id = "23"> <Name> Li Ming </Name> <age> 30 </age> </person> <person id = "20"> <name> Li xiangmei </Name> <age> 25 </age> </person> </persons>

2. Write a sax-parsed class in the service

Package COM. example. service; import Java. util. arraylist; import Java. util. list; import Org. XML. sax. attributes; import Org. XML. sax. saxexception; import Org. XML. sax. helpers. defaulthandler; import COM. example. domain. person; public class xmlcontenthandler extends defaulthandler {// The resolved person object is stored in the private list <person> persons in the list set; // parse the current person object public person currentperson; // declare the tag name Public String tagname; // obtain the resolution Institute Some person objects are public list <person> getpersons () {return persons;} @ overridepublic void characters (char [] CH, int start, int length) throws saxexception {super. characters (CH, start, length); // first, judge whether the tagname is null if (tagname! = NULL) {string data = new string (CH, start, length); // checks whether the tag is empty if (tagname. equals ("name") {currentperson. setname (data);} else if (tagname. equals ("Age") {// determine whether the tag is agecurrentperson. setage (short) integer. parseint (data) ;}}@ overridepublic void enddocument () throws saxexception {super. enddocument () ;}@ overridepublic void endelement (string Uri, string localname, string QNAME) throws saxexception {super. endelement (Uri, localname, QNAME); // when the person Tag ends, store the person object in the set if (localname. equals ("person") {persons. add (currentperson); currentperson = NULL;} This. tagname = NULL;}/*** event triggered at the beginning of the document */@ overridepublic void startdocument () throws saxexception {super. startdocument (); Persons = new arraylist <person> () ;}@ overridepublic void startelement (string Uri, string localname, string QNAME, attributes) throws saxexception {super. startelement (Uri, localname, QNAME, attributes); // determine whether the parsed tag is personif (localname. equals ("person") {currentperson = new person (); // parse the value of the ID attribute and assign the ID to the currentperson object currentperson. setid (integer. parseint (attributes. getvalue (0);} This. tagname = localname ;}}

3. Get the operations of the sax class in the activity

Package COM. example. lession03_xml; import Java. io. inputstream; import Java. util. list; import javax. XML. parsers. saxparser; import javax. XML. parsers. saxparserfactory; import COM. example. domain. person; import COM. example. service. xmlcontenthandler; import COM. example. service. xmldomservice; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. view. view; import android. view. view. onclicklistener; import android. view. inputmethod. inputbinding; import android. widget. button; import android. widget. toast; public class xmlactivity extends activity {// declare the public button btn_sax, btn_dom, btn_pull; Public xmldomservice; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // sets the displayed view setcontentview (R. layout. activity_xml); xmldomservice = new xmldomservice (); // obtain the component btn_sax = (button) findviewbyid (R. id. btn_sax); btn_dom = (button) findviewbyid (R. id. btn_dom); btn_pull = (button) findviewbyid (R. id. btn_pull); // register the event listener for the button (New myonclicklistener (); btn_dom.setonclicklistener (New myonclicklistener (); btn_pull.setonclicklistener (New myonclicklistener ());} @ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). inflate (R. menu. XML, menu); Return true;} // Anonymous class myonclicklistener implements onclicklistener {@ overridepublic void onclick (view v) {int id = v. GETID (); Switch (ID) {case R. id. btn_sax: Toast. maketext (xmlactivity. this, "using sax Parsing", toast. length_long ). show (); try {// The factory object saxparserfactory factory parsed by sax = saxparserfactory. newinstance (); // get the SAX Parser saxparser = factory. newsaxparser (); // create the handler object xmlcontenthandler handlerservice = new xmlcontenthandler (); inputstream is = getassets (). open ("csdn. XML "); // parse saxparser directly. parse (is, handlerservice); // get toast through the handlerservice object. maketext (xmlactivity. this, "----" + handlerservice, toast. length_long ). show ();} catch (exception e) {e. printstacktrace ();} break; case R. id. btn_dom: inputstream is = NULL; try {// get the input stream object for reading the file is = getassets (). open ("csdn. XML "); // use Dom to parse list <person> Persons = xmldomservice. parsexml (is); // simple test // toast. maketext (xmlactivity. this, "" + persons. get (0 ). getname (), toast. length_long ). show (); toast. maketext (xmlactivity. this, "using Dom Parsing" + persons. get (0 ). getname (), toast. length_long ). show ();} catch (exception e) {e. printstacktrace ();} break; case R. id. btn_pull: Toast. maketext (xmlactivity. this, "using pull Parsing", toast. length_long ). show (); break; default: break ;}}}}

 

 

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.