xml文件放置在res\xml目录下,通过Resources.get
XML()方法访问。
class="java" name="code">
package com.jiang.ch3.xml;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestXmlActivity extends Activity {
private TextView myTextView = null;
private Button myButton = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_xml);
myTextView = (TextView) findViewById(R.id.xmlContentTextView01);
myButton = (Button) findViewById(R.id.xmlTestButton1);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int counter = 0;
StringBuilder sb = new StringBuilder("");
Resources r = getResources();
XmlResourceParser xrp = r.getXml(R.xml.test);
try {
// 当没有达到xml的逻辑结束终点
// getEventType方法返回读取xml当前的事件
while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xrp.getEventType() == XmlResourceParser.START_TAG) {
String name = xrp.getName();
System.out.println(name);
if (name.equals("customer")) // 查找符合条件的
{
counter++; // 统计第几个节点
sb.append("第" + counter + "条客户信息:" + "\n");
sb.append(xrp.getAttributeValue(0) + "\n");
sb.append(xrp.getAttributeValue(1) + "\n");
sb.append(xrp.getAttributeValue(2) + "\n");
sb.append(xrp.getAttributeValue(3) + "\n");
}
}// 当读取到xml节点是一个元素的尾标记时
else if (xrp.getEventType() == XmlPullParser.END_TAG) {
// 控制台输出xml节点结束
System.out.println(xrp.getName() + "---End!");
} // 当读取到xml节点是文本时
else if (xrp.getEventType() == XmlPullParser.TEXT) {
// 输出文本
sb.append("姓名:" + xrp.getText() + "\n\n");
}
xrp.next();
}
myTextView.setText(sb.toString());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}