1. Create a new XML file and place it in the Res/xml directory
1 <?xml version= "1.0" encoding= "Utf-8"?>2 <citys>3 <city count= "1400" name= "Shenzhen" > Guangdong </city>4 <city count= "name=" " Guangzhou" > Guangdong </city>5 <city count= "" name= "Wuhan" > Hubei </city>6 </citys>
2. The layout file code is as follows:
1<?xml version= "1.0" encoding= "Utf-8"?>2<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"3Android:layout_width= "Fill_parent"4android:layout_height= "Fill_parent"5android:orientation= "Vertical" >6 7<Button8Android:id= "@+id/btn"9Android:layout_width= "Wrap_content"Tenandroid:layout_height= "Wrap_content" Oneandroid:text= "@string/btnmsg"/> A -<EditText -Android:id= "@+id/edit" theAndroid:layout_width= "Fill_parent" -android:layout_height= "Wrap_content"/> - -</LinearLayout>
3. Background Java parsing code is as follows:
1 PackageYmw.main;2 3 Importjava.io.IOException;4 5 Importorg.xmlpull.v1.XmlPullParserException;6 7 ImportYMW.MAIN.R;8 9 Importandroid.app.Activity;Ten ImportAndroid.content.res.XmlResourceParser; One ImportAndroid.os.Bundle; A ImportAndroid.view.View; - ImportAndroid.widget.Button; - ImportAndroid.widget.EditText; the - Public classXmlresourceparsersampleactivityextendsActivity { - @Override - Public voidonCreate (Bundle savedinstancestate) { + Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.main); +Button BTN =(Button) Findviewbyid (R.ID.BTN); A FinalEditText edit =(EditText) Findviewbyid (r.id.edit); atBtn.setonclicklistener (NewView.onclicklistener () { - @Override - Public voidOnClick (View v) { -Xmlresourceparser xpr = xmlresourceparsersampleactivity. This -. Getresources (). GETXML (R.xml.myxml);//Locate the XML file -StringBuilder SB =NewStringBuilder (); in Try { - //Loop parsing to while(Xpr.geteventtype ()! =xmlresourceparser.end_document) { + if(Xpr.geteventtype () = =Xmlresourceparser.start_tag) { - //gets the label name of the label theString name =xpr.getname (); * if(Name.equals ("City")) { $Sb.append ("City Name:" + xpr.getattributevalue (1)Panax Notoginseng+ "\ n"); -Sb.append ("Population:" the+ Xpr.getattributevalue (NULL, "Count") ++ "Million \ n"); A Try { theSb.append ("Province:" + xpr.nexttext () + "\ n"); +}Catch(IOException e) { - e.printstacktrace (); $ } $ } - } - Try { the Xpr.next (); -}Catch(IOException e) {Wuyi e.printstacktrace (); the } - } Wu Edit.settext (sb.tostring ()); -}Catch(xmlpullparserexception e) { About e.printstacktrace (); $ } - } - }); - } A +}
Android Xmlpull method Parsing xml file