Android xmlpull 方式解析xml文件

时间:2021-10-30 11:28:42

1.新建一个xml文件,放在res/xml目录下

 <?xml version="1.0" encoding="utf-8"?>
<citys>
<city count="1400" name="深圳">广东</city>
<city count="1500" name="广州">广东</city>
<city count="1000" name="武汉">湖北</city>
</citys>

2.布局文件代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnmsg" /> <EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content" /> </LinearLayout>

3.后台java解析代码如下:

 package ymw.main;

 import java.io.IOException;

 import org.xmlpull.v1.XmlPullParserException;

 import ymw.main.R;

 import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText; public class XmlResourceParserSampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
final EditText edit = (EditText) findViewById(R.id.edit);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
XmlResourceParser xpr = XmlResourceParserSampleActivity.this
.getResources().getXml(R.xml.myxml);// 找到xml文件
StringBuilder sb = new StringBuilder();
try {
// 循环解析
while (xpr.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xpr.getEventType() == XmlResourceParser.START_TAG) {
// 获取标签的标签名
String name = xpr.getName();
if (name.equals("city")) {
sb.append("城市名称:" + xpr.getAttributeValue(1)
+ "\n");
sb.append("人口:"
+ xpr.getAttributeValue(null, "count")
+ "万\n");
try {
sb.append("所属省份:" + xpr.nextText() + "\n\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
xpr.next();
} catch (IOException e) {
e.printStackTrace();
}
}
edit.setText(sb.toString());
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
});
} }