標籤:
1.建立一個xml檔案,放在res/xml目錄下
1 <?xml version="1.0" encoding="utf-8"?>2 <citys>3 <city count="1400" name="深圳">廣東</city>4 <city count="1500" name="廣州">廣東</city>5 <city count="1000" name="武漢">湖北</city>6 </citys>
2.布局檔案代碼如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:id="@+id/btn" 9 android:layout_width="wrap_content"10 android:layout_height="wrap_content"11 android:text="@string/btnmsg" />12 13 <EditText14 android:id="@+id/edit"15 android:layout_width="fill_parent"16 android:layout_height="wrap_content" />17 18 </LinearLayout>
3.後台java解析代碼如下:
1 package ymw.main; 2 3 import java.io.IOException; 4 5 import org.xmlpull.v1.XmlPullParserException; 6 7 import ymw.main.R; 8 9 import android.app.Activity;10 import android.content.res.XmlResourceParser;11 import android.os.Bundle;12 import android.view.View;13 import android.widget.Button;14 import android.widget.EditText;15 16 public class XmlResourceParserSampleActivity extends Activity {17 @Override18 public void onCreate(Bundle savedInstanceState) {19 super.onCreate(savedInstanceState);20 setContentView(R.layout.main);21 Button btn = (Button) findViewById(R.id.btn);22 final EditText edit = (EditText) findViewById(R.id.edit);23 btn.setOnClickListener(new View.OnClickListener() {24 @Override25 public void onClick(View v) {26 XmlResourceParser xpr = XmlResourceParserSampleActivity.this27 .getResources().getXml(R.xml.myxml);// 找到xml檔案28 StringBuilder sb = new StringBuilder();29 try {30 // 迴圈解析31 while (xpr.getEventType() != XmlResourceParser.END_DOCUMENT) {32 if (xpr.getEventType() == XmlResourceParser.START_TAG) {33 // 擷取標籤的標籤名34 String name = xpr.getName();35 if (name.equals("city")) {36 sb.append("城市名稱:" + xpr.getAttributeValue(1)37 + "\n");38 sb.append("人口:"39 + xpr.getAttributeValue(null, "count")40 + "萬\n");41 try {42 sb.append("所屬省份:" + xpr.nextText() + "\n\n");43 } catch (IOException e) {44 e.printStackTrace();45 }46 }47 }48 try {49 xpr.next();50 } catch (IOException e) {51 e.printStackTrace();52 }53 }54 edit.setText(sb.toString());55 } catch (XmlPullParserException e) {56 e.printStackTrace();57 }58 }59 });60 }61 62 }
Android xmlpull 方式解析xml檔案