標籤:
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{@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnTest = (Button) this.findViewById(R.id.btnTest);btnTest.setOnClickListener(new OnClickListener(){@Overridepublic 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();}}});}@Overridepublic 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檔案