There are three main ways to parse XML in Android: sax, dom and pull. For its content, please refer to: http://blog.csdn.net/liuhe688/article/details/6415593 This article will mainly introduce the pull parser to parse xml files, the environment is ubuntu 12.04+ intelij 13.1 + android sdk 2.1 2. Parse an xml file: assets/person.xml
1. Create an XML project, the steps are as follows:
<?xml version=”1.0″ encoding=”UTF-8″?>
persons
person id=”1101″
nameamos</name
age30</age
</person
person id=”1102″
nametom</name
age18</age
</person
</persons
com/amos/xml/domain/Person.java
package com.amos.xml.domain;/**
* Created by amosli on 14-6-3.
*/public class Person {
private String name;
private Integer age;
private Integer id;public Integer getAge() {
return age;
}public void setAge(Integer age) {
if (age 100) {
this.age = 0;
} else {
this.age = age;
}
}public Integer getId() {
returnid;
}public void setId(Integer id) {
this.id =id;
}public String getName() {
returnname;
}
public void setName(String name) {
this.name =name;
}
}
com/amos/xml/service/PersonService.java
package com.amos.xml.service;import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.util.Xml;
import com.amos.xml.domain.Person;
import org.xmlpull.v1.XmlPullParser;importjava.io.InputStream;
import java.util.ArrayList;
importjava.util.List;/**
* Created by amosli on 14-6-3.
*/
public class PersonService {
private Context context;public PersonService(Context context) {
this.cOntext= context;
}/**
* Convert the input stream parsing of person.xml into a list collection
*
* @param
* @return
*/
public List getPersons(String filename) {AssetManager manager
= context.getAssets();
//Initialize project.
List persOns= null;
Person person = null;try {
InputStream inputStream = manager.open(filename);
//Use xmlpullparser to parse under android
XmlPullParser xmlPullParser = Xml.newPullParser();
//Set some parameters of xmlpullparser
xmlPullParser.setInput(inputStream, “utf-8”);//Get the event type corresponding to the pull parser
int eventType = xmlPullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
caseXmlPullParser.START_DOCUMENT:
persons = new ArrayList();
break;case XmlPullParser.START_TAG:
if (xmlPullParser. getName(). equals(“person”)) {
person= new Person();
String id = xmlPullParser.getAttributeValue(0);
Log.d(“person.id”, id);
person. setId(Integer. parseInt(id));
eventType = xmlPullParser. next();
} else if (xmlPullParser.getName().equals(“name”)) {
String name = xmlPullParser.nextText();
Log.d(“person.name”, name);
person. setName(name);
eventType = xmlPullParser. next();
} else if (xmlPullParser.getName().equals(“age”)) {
String age = xmlPullParser.nextText();
Log.d(“person.age”, age);
person.setAge(Integer.valueOf(age));
eventType = xmlPullParser. next();
}
break;
case XmlPullParser.END_TAG:
if (xmlPullParser. getName(). equals(“person”)) {
persons. add(person);
person= null;
}
break;
}
eventType = xmlPullParser. next();
}}
catch (Exception e) {
e.printStackTrace();
}
return persons;
}
}
Note: The analysis here mainly uses eventType (event type), if it is START_DOCUMENT, it means reading the beginning of the document, if is START_TAG, it means Read the start position of the element in the document, such as , and the similar end positions are END_DOCUMENT and END_TAG; among them, pay attention to judging what the name of the event type starts, and when taking the value, pay attention to the different positions The value method is also different, such as , then the way to get the id is getAttributeValue(int index), and get the amos, you need to use the nextText() method to get the value.
/com/amos/xml/MyActivity.java
package com.amos.xml;import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.amos.xml.domain.Person;
import com.amos.xml.service.PersonService;importjava.util.List;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView show_users = (TextView) findViewById(R.id.show_users);
PersonService personService = new PersonService(this);
StringBuilder stringBuilder = new StringBuilder();
List persOns= personService.getPersons(“person.xml”);
for (Person person : persons) {
stringBuilder.append(” ” + person.getName()).append(“:”).append(person.getAge());
}
System.out.println(“stringBuilder:” + stringBuilder);
show_users.setText(stringBuilder);
Toast.makeText(this, “Data written successfully!” + stringBuilder, Toast.LENGTH_LONG);
}
}
Here I define a TextView on the main interface to display the content of the read xml file, the effect is shown in the following figure:
3. Test case
First, add the necessary configuration: AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.amos.xml”
android:versionCode=”1″
android:versionName=”1.0″>
uses-sdk android:minSdkVersion=”7″/>
application android:label=”@string/app_name”
uses-library android:name=”android.test.runner”/ >
activity android:name=”MyActivity”
android:label=”@string/app_name”>
intent-filter
action android:name=”android.intent.action.MAIN”/>
category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter
</activity
</application>
instrumentation android:name=”android.test.InstrumentationTestRunner”
android:targetPackage=”com.amos.xml”/>
</manifest>
The part in bold is added to the project later.
Second, write a testcase: /com/amos/xml/test/TestService.java
package com.amos.xml.test;import android.test.AndroidTestCase;
import com.amos.xml.domain.Person;
import com.amos.xml.service.PersonService;import java.util.List;
/**
* Created by amosli on 14-6-3.
*/
public class TestService extends AndroidTestCase {public void testGetPersons() throws Exception {
Person> persOns= personService. getPersons(“person.xml”);
PersonService persOnService= new PersonService(getContext());
List
for (Person person : persons) {
System.out.println(person.getName());
}
}
}
Here, if you want to view the running steps of each step, you can add a breakpoint. The shortcut keys in intelij are F8 (step over), F7 (step
into), F9(Resume program).
Git address of this article: https://github.com/amosli/android_basic/tree/xml
Android development learning — use XmlPullParser to parse xml files,,
Android development learning — use XmlPullParser to parse xml files
.println(“stringBuilder:” + stringBuilder);
show_users.setText(stringBuilder);
Toast.makeText(this, “Data written successfully!” + stringBuilder, Toast.LENGTH_LONG);
}
}
Here I define a TextView on the main interface to display the content of the read xml file, the effect is shown in the following figure:
3. Test case
First, add the necessary configuration: AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.amos.xml”
android:versionCode=”1″
android:versionName=”1.0″>
uses-sdk android:minSdkVersion=”7″/>
application android:label=”@string/app_name”
uses-library android:name=”android.test.runner”/ >
activity android:name=”MyActivity”
android:label=”@string/app_name”>
intent-filter
action android:name=”android.intent.action.MAIN”/>
category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter
</activity
</application>
instrumentation android:name=”android.test.InstrumentationTestRunner”
android:targetPackage=”com.amos.xml”/>
</manifest>
The part in bold is added to the project later.
Second, write a testcase: /com/amos/xml/test/TestService.java
package com.amos.xml.test;import android.test.AndroidTestCase;
import com.amos.xml.domain.Person;
import com.amos.xml.service.PersonService;import java.util.List;
/**
* Created by amosli on 14-6-3.
*/
public class TestService extends AndroidTestCase {public void testGetPersons() throws Exception {
Person> persOns= personService. getPersons(“person.xml”);
PersonService persOnService= new PersonService(getContext());
List
for (Person person : persons) {
System.out.println(person.getName());
}
}
}
Here, if you want to view the running steps of each step, you can add a breakpoint. The shortcut keys in intelij are F8 (step over), F7 (step
into), F9(Resume program).
Git address of this article: https://github.com/amosli/android_basic/tree/xml
Android development learning — use XmlPullParser to parse xml files,,
Android development learning — use XmlPullParser to parse xml files