<?xml version="1.0" encoding="utf-8"?>
<books>
<book price="99.0" data="2008年">正見-佛陀的證悟</book>
<book price="89.0" data="2008年">遇見未知的自己</book>
<book price="69.0" data="2008年">不一樣的煙火</book>
</books>
2、顯示的佈局xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.ui.demo.custom.XmlResActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲取資源"
android:onClick="getResource"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/show"/>
</LinearLayout>
3、讀取xml內容public class XmlResActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml_res);
}
public void getResource(View view)
{
//根據XMl資源的ID獲取解析該資源的解析器
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.books);
StringBuilder stringBuilder = new StringBuilder("");
try
{
while (xmlResourceParser.getEventType() != XmlPullParser.END_DOCUMENT)
{
//還沒有到Xml文檔的結尾處
if (xmlResourceParser.getEventType() == XmlPullParser.START_TAG)
{
String tagName = xmlResourceParser.getName();
//如果是books標籤
if (tagName.equals("book"))
{
String bookName = xmlResourceParser.getAttributeValue(null,"price");
stringBuilder.append("價格:");
stringBuilder.append(bookName);
String bookPrice = xmlResourceParser.getAttributeValue(null,"data");
stringBuilder.append(" 出版日期:");
stringBuilder.append(bookPrice);
stringBuilder.append(" 書名:");
stringBuilder.append(xmlResourceParser.nextText());
}
stringBuilder.append("\n");
}
xmlResourceParser.next();
}
TextView show = (TextView) findViewById(R.id.show);
show.setText(stringBuilder.toString());
}
catch (XmlPullParserException | IOException e)
{
e.printStackTrace();
}
}
}