1. The XML file to parse is as follows
<?XML version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?><Weather> < City> <name>Shenzhen</name> <Temp>18°</Temp> <PM25>30</PM25> </ City> < City> <name>Shanghai</name> <Temp>13°</Temp> <PM25>25</PM25> </ City> < City> <name>Beijing</name> <Temp>6°</Temp> <PM25>800</PM25> </ City></Weather>
2. The corresponding JavaBean for each city node are as follows:
Public classCity {PrivateString name; PrivateString temp; PrivateString PM25; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString gettemp () {returntemp; } Public voidsettemp (String temp) { This. temp =temp; } PublicString getPm25 () {returnPM25; } Public voidsetPm25 (String pm25) { This. PM25 =PM25; } PublicCity (string name, String temp, string pm25) {Super(); This. Name =name; This. temp =temp; This. PM25 =PM25; } PublicCity () {Super(); } @Override PublicString toString () {return"City [name=" + name + ", temp=" + temp + ", pm25=" + PM25 + "]"; } }3. The Mainactivity.java for parsing are as follows:
Public classMainactivityextendsActivity {List<City>CityList; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); } Public voidClick (View v) {//Parsing XML Files//1. Get the resource fileInputStream is = getClassLoader (). getResourceAsStream ("Weather.xml"); //2. Get the Parser objectXmlpullparser XP =Xml.newpullparser (); Try { //3. Initializing XP objectsXp.setinput (IS, "GBK");//Depending on the encoding saved by the file//4. Start parsing//gets the event type of the current node intType =Xp.geteventtype (); City City=NULL; while(Type! =xmlpullparser.end_document) { //determine which node is currently resolved to decide what you want to do Switch(type) { CaseXmlpullparser.start_tag://gets the name of the current node if("Weather". Equals (Xp.getname ())) {CityList=NewArraylist<city>(); } Else if("City". Equals (Xp.getname ())) { City=NewCity (); } Else if("Name". Equals (Xp.getname ())) { //gets the text of the next node of the current node, moving the pointer to the end node of the current nodeString name =Xp.nexttext (); City.setname (name); } Else if("Temp". Equals (Xp.getname ())) { //gets the text of the next node of the current node, moving the pointer to the end node of the current nodeString temp =Xp.nexttext (); City.settemp (temp); } Else if("PM25". Equals (Xp.getname ())) { //gets the text of the next node of the current node, moving the pointer to the end node of the current nodeString PM25 =Xp.nexttext (); CITY.SETPM25 (PM25); } Break; CaseXmlpullparser.end_tag:if("City". Equals (Xp.getname ())) {Citylist.add (city); } Break; } //move the pointer to the next nodeType =Xp.next (); } for(city c:citylist) {System.out.println (c.tostring ()); } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }
Android Basic--xml parsing (Xmlpullparser)