Parse XML files using DOM 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 DOM parsing operation in the service

Package COM. example. service; import Java. io. inputstream; import Java. util. arraylist; import Java. util. list; import javax. XML. parsers. documentbuilder; import javax. XML. parsers. documentbuilderfactory; import Org. w3C. dom. document; import Org. w3C. dom. element; import Org. w3C. dom. node; import Org. w3C. dom. nodelist; import COM. example. domain. person; public class xmldomservice {public list <person> parsexml (inputstream is) {list <person> List = new arraylist <person> (); // create the DOM factory object documentbuilderfactory factory = documentbuilderfactory. newinstance (); try {// documentbuilder object documentbuilder builder = factory. newdocumentbuilder (); // obtain the Document Object document = builder. parse (is); // obtain the rootelement root = Document of the Document Object. getdocumentelement (); // obtain all the person node objects in the root node of persons. nodelist personnodes = root. getelementsbytagname ("person"); // traverses all the person nodes for (INT I = 0; I <personnodes. getlength (); I ++) {person = new person (); // obtain the Node object element personnode = (element) personnodes corresponding to the index based on item (index. item (I); // specific person node // sets the ID attribute value "person. setid (integer. parseint (personnode. getattribute ("ID"); // get all the byte points under the node nodelist personchildnodes = personnode. getchildnodes (); // traverses the byte points of person for (INT Index = 0; index <personchildnodes. getlength (); index ++) {// obtain the subnode node = personchildnodes. item (INDEX); // determines whether a node is an element node. If (node. getnodetype () = node. element_node) {// converts a node to an element = (element) node; // determines whether the element node is a name element node if ("name ". equals (element. getnodename () {person. setname (element. getfirstchild (). getnodevalue ();} else if ("age ". equals (element. getnodename () {// determines whether it is an age node person. setage (new short (element. getfirstchild (). getnodevalue () ;}}// Add the person object to the list in the set. add (person);} // close the input stream is. close ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();} return list ;}}

3. Display operations in 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 ;}}}}

 

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.