首页 > 代码库 > android学习笔记36——使用原始XML文件

android学习笔记36——使用原始XML文件

XML文件

android中使用XML文件,需要开发者手动创建res/xml文件夹。

实例如下:

book.xml==><?xml version="1.0" encoding="utf-8"?><books>    <book publishDate="2016.05.05" price="88.6">android学习笔记</book>    <book publishDate="2016.06.06" price="88.6">android解密</book>    <book publishDate="2016.08.08" price="88.6">android深入浅出</book></books>布局文件==》<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:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:id="@+id/btnTest"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="Test" >    </Button>    <EditText        android:id="@+id/edit"        android:layout_width="match_parent"        android:layout_height="wrap_content" >    </EditText></LinearLayout>代码实现==》package com.example.myxml;import org.xmlpull.v1.XmlPullParserException;import android.R.xml;import android.os.Bundle;import android.app.Activity;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.EditText;public class MainActivity extends Activity{	@Override	protected void onCreate(Bundle savedInstanceState)	{		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		Button btnTest = (Button) this.findViewById(R.id.btnTest);		btnTest.setOnClickListener(new OnClickListener()		{			@Override			public void onClick(View v)			{				XmlResourceParser xrp = getResources().getXml(R.xml.books);				StringBuilder sb = new StringBuilder();				try				{					while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT)					{						if (xrp.getEventType() == XmlResourceParser.START_TAG)// 如果遇到开始标签						{							// String tagName = xrp.getName();							if (xrp.getName().equals("book"))							{								// 根据名称获取属性值								sb.append("price: ");								sb.append(xrp.getAttributeValue(null, "price"));								sb.append("\n");								// 根据索引获取属性值								sb.append("publishDate: ");								sb.append(xrp.getAttributeValue(0));								sb.append("\n");								sb.append("bookName:	");								// 获取XML节点的文本信息								sb.append(xrp.nextText());							}							sb.append("\n");						}						xrp.next();// 获取解析器的下一个事件					}					EditText edit = (EditText) findViewById(R.id.edit);					edit.setText(sb.toString());				} catch (Exception 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;	}}

运行效果:

技术分享

 

android学习笔记36——使用原始XML文件