In this chapter, we will learn the XML parser in Android. Android comes with three XML parser, including pull, sax, and Dom parser, both pull and sax adopt event-driven parser. The advantage is that the memory usage is small and the processing speed is fast. Dom puts the entire XML into the memory for further parsing, and the processing speed is slightly lower, however, Dom also has its own advantages. You can add nodes when parsing them. OK. Let's take a look at the XML file to be parsed.
<? XML version = "1.0" encoding = "UTF-8"?> <Persons> <person id = "1"> <status> big brother </status> <Name> Sun Wukong </Name> <tool> golden hoop </tool> <number> killed 50 monsters </number> </person> <person id = "2"> <status> diaodi </status> <Name> pig </Name> <tool> nine-tooth dingtalk </tool> <number> killed 40 monsters </number> </person> <person id = "3"> <status> three younger siblings </status> <Name> Sha monk </Name> <tool> demon master pin </tool> <number> killed 30 monsters </number> </person> </persons>
Some personal information and other specific information are defined here. Well, save it to the SD directory of the simulator. Next, we will first define JavaBean, person. Java
public class Person{private String id;private String status;private String name;private String tool;private String number;public String getId(){return id;}public void setId(String id){this.id = id;}public String getStatus(){return status;}public void setStatus(String status){this.status = status;}public String getName(){return name;}public void setName(String name){this.name = name;}public String getTool(){return tool;}public void setTool(String tool){this.tool = tool;}public String getNumber(){return number;}public void setNumber(String number){this.number = number;}@Overridepublic String toString(){return "Person [id=" + id + ", status=" + status + ", name=" + name+ ", tool=" + tool + ", number=" + number + "]";}}
Corresponding to the data in the above XML file, the next step is to focus on it, so be good at learning. Haha, pull parsing class pullhandler. Java
Import Java. io. inputstream; import Java. util. arraylist; import Java. util. list; import Org. xmlpull. v1.xmlpullparser; import android. util. XML; public class pullhandler {private inputstream input; private list <person> persons; private person; Public pullhandler () {} public void setinput (inputstream input) {This. input = input;} public pullhandler (inputstream input) {This. input = input;} public list <person> get Persons () {try {xmlpullparser parser = xml. newpullparser (); parser. setinput (input, "UTF-8"); int eventtype = parser. geteventtype (); While (eventtype! = Xmlpullparser. end_document) {Switch (eventtype) {// xmlpullparser. start_document indicates the start document event case xmlpullparser. start_document: Persons = new arraylist <person> (); break; // xmlpullparser. start_tag: start tag case xmlpullparser. start_tag: // parser. getname () Get the node name string tag = parser. getname (); If ("person ". equals (TAG) {person = new person (); // parser. getattributename (0) gets the first attribute value in <person id = "1"> string id = parser. geta Ttributevalue (0); person. setid (ID) ;}if (null! = Person) {If ("status ". equals (TAG) {// parser. nexttext (); obtain the person of the next text node. setstatus (parser. nexttext ();} If ("name ". equals (TAG) {person. setname (parser. nexttext ();} If ("tool ". equals (TAG) {person. settool (parser. nexttext ();} If ("number ". equals (TAG) {person. setnumber (parser. nexttext () ;}} break; // xmlpullparser. end_tag: end tag case xmlpullparser. end_tag: If ("person ". equals (parser. getname () {persons. add (person); person = NULL;} break;} // event = parser. next (); continue to the next element eventtype = parser. next ();} input. close (); return persons;} catch (exception e) {e. printstacktrace ();} return NULL ;}}
OK. The parsing class is finished. Test it. Use the unit test in the previous lesson. unit test is very important for every small method, this should be able to solve the problem in a timely manner. Oh, I'm almost like a Tang monk, Amitabha. If I don't know about the Japanese stamp yuan test, let's take a look.
Android [intermediate tutorial] Chapter 4 unit test androidtestcase
Import Java. io. file; import Java. io. fileinputstream; import Java. util. list; import android. OS. environment; import android. test. androidtestcase; public class pullhandlertest extends androidtestcase {public void testgetpersons () {// obtain the file path file sd_files = environment in the current SD directory. getexternalstoragedirectory (); // get persons. path of the XML file. Here I have sdcard/persons. xmlstring file_path = sd_files.getname () + file. separator + "persons. XML "; try {fileinputstream FCM = new fileinputstream (new file (file_path); pullhandler = new pullhandler (FS); List <person> Persons = pullhandler. getpersons (); // output the data system in persons. out. println (persons);} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
The test class has been written. Test it. OK. The next step is to define main. xml.
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" three younger siblings of Tang Seng "Android: layout_height =" wrap_content "Android: id = "@ + ID/textview1" Android: paddingleft = "10dip" Android: paddingbottom = "10dip"> </textview> <listview Android: id = "@ + ID/xml_list" Android: layout_height = "wrap_content" Android: layout_width = "match_parent"> </listview> </linearlayout>
A listview and a textview are defined. listview is used to display data in XML.
Define another list_item.xml to display the data style of each row.
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <linearlayout Android: layout_height = "wrap_content" Android: Id = "@ + ID/linearlayout1" Android: layout_width = "match_parent"> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" ID: "Android: paddingleft =" 10dp "> </textview> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" textview "Android: Id =" @ + ID/ID "> </textview> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" textview "Android: Id =" @ + ID/Name "Android: paddingleft = "30dp"> </textview> </linearlayout> <linearlayout Android: layout_height = "wrap_content" Android: Id = "@ + ID/linearlayout2" Android: layout_width = "match_parent"> <textview Android: layout_height = "wrap_content" Android: layout_width = "wrap_content" Android: text = "killed" Android: paddingleft = "10dp"> </textview> <textview Android: text = "textview" Android: Id = "@ + ID/number" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: textcolor = "# ff0000"> </textview> <textview Android: text = "only monsters" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </textview> </linearlayout>
Okay, all of them are defined. Finally, our activity is finished.
Import Java. io. file; import Java. io. fileinputstream; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import Java. util. map; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. widget. listview; import android. widget. simpleadapter; public class pullactivity extends activity {private listview; private simpleadapter adapter; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. xml_handler); listview = (listview) findviewbyid (R. id. xml_list); try {// getadapter ();} catch (exception e) {e. printstacktrace ();} listview. setadapter (adapter);} // custom adaptation method private void getadapter () throws exception {list <Map <string, string> lists = new arraylist <Map <string, string >>(); // This part is the part of file sd_files = environment we used for testing. getexternalstoragedirectory (); string file_path = sd_files.getname () + file. separator + "persons. XML "; fileinputstream input = new fileinputstream (new file (file_path); pullhandler = new pullhandler (input); List <person> Persons = pullhandler. getpersons (); // convert the data in persons to arraylist <Map <string, string>, because simpleadapter uses this type of data to adapt Map <string, string> map; for (person P: Persons) {map = new hashmap <string, string> (); map. put ("ID", p. GETID (); map. put ("status", p. getstatus (); map. put ("name", p. getname (); map. put ("tool", p. gettool (); map. put ("Number", p. getnumber (); lists. add (MAP) ;}// keystring [] From = {"ID", "status", "name", "tool", in hashmap <string, string> ", "Number"}; // idint [] to = {R. id. item_id, R. id. item_status, R. id. item_name, R. id. item_tool, R. id. item_number}; adapter = new simpleadapter (this, lists, R. layout. handler_list_item, from, );}}
Okay, that's the end.
This chapter is a bit long. I hope you can read it all. We still need to use the template here for the following sax parsing and Dom parsing. Thank you.