标签:
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 <EditText
14 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 @Override
18 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 @Override
25 public void onClick(View v) {
26 XmlResourceParser xpr = XmlResourceParserSampleActivity.this
27 .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 }
标签:
原文地址:http://www.cnblogs.com/_ymw/p/4224530.html