前端之家收集整理的这篇文章主要介绍了
自定义XML文件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1、创建xml
文件内容,books.xml
<?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();
}
}
}