1、工程目录
2、TestXMLActivity.java
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.example.test_resource.R;
public class TestXMLActivity extends Activity {
private TextView myTextView;
private Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_xml);
myButton = (Button) findViewById(R.id.xmlTestButton01);
myTextView = (TextView) findViewById(R.id.xmlContextTextView01);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int counter = 0;
StringBuilder sb = new StringBuilder("");
Resources r = getResources();
XmlResourceParser xrp = r.getXml(R.xml.test);
try {
while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xrp.getEventType() == XmlResourceParser.START_TAG) {
String name = xrp.getName();
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\n");
}
} else if (xrp.getEventType() == XmlPullParser.END_TAG) {
} else if (xrp.getEventType() == XmlPullParser.TEXT) {
}
xrp.next();
}
myTextView.setText(sb.toString());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
3、布局文件test_xml.xml
<pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/xmlTestButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获得XML内容" />
<TextView
android:id="@+id/xmlContextTextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
4、/res/xml/test.xml
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<resources>
<customer name="tom" age="20" email="tom@yahoo.com" gender="male" />
<customer name="kite" age="21" email="kite@yahoo.com" gender="male" />
</resources>
遇到的问题:test.xml总是出现错误,必须把它放在/res/xml文件夹下才能运行成功!