res\xml\fruit.xml
<?xml version="1.0" encoding="utf-8"?> <fruits> <fruit position="1" context="Oranges" /> <fruit position="2" context="bananas" /> <fruit position="3" context="pears" /> <fruit position="4" context="apples" /> <fruit position="5" context="watermelon" /> </fruits>
Tutorial_Data_XmlPullParserActivity.java
package com.powenko.Tutorial_Data_XmlPullParser; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class Tutorial_Data_XmlPullParserActivity extends Activity { private static final String APP_TAG = "powenko.com"; /** Called when the activity is first created. */ TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView01); Fun_XmlPullParser(); } public void Fun_XmlPullParser(){ XmlPullParser parser = getResources().getXml(R.xml.fruit); StringBuilder stringBuilder = new StringBuilder(); try { while (parser.next() != XmlPullParser.END_DOCUMENT) { String name = parser.getName(); String position = null; String brand = null; if((name != null) && name.equals("fruit")) { int size = parser.getAttributeCount(); for(int i = 0; i < size; i++) { String attrName = parser.getAttributeName(i); String attrValue = parser.getAttributeValue(i); if((attrName != null) && attrName.equals("position")) { position = attrValue; } else if ((attrName != null) && attrName.equals("context")) { brand = attrValue; } } if((position != null) && (brand != null)) { stringBuilder.append(position + ", " + brand + "\n"); } } textView.setText(stringBuilder.toString()); } }catch(Exception e) { Log.e(APP_TAG, e.getMessage()); } } }
res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="hello" android:id="@+id/textView01" /> </LinearLayout>
sample code:
Tutorial_Data_XmlPullParser