利用pull解析器解析xml文件

下面我们再看pull解析xml文件

我们先看项目代码:

1、先给出要解析的xml文件jindegege.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="02">
<name>jindegege</name>
<age>28</age>
</person>
<person id="10">
<name>liubiyu</name>
<age>27</age>
</person>
</persons>


2、给出业务类PULLPersonService.java

 
 
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;


import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;


import android.util.Xml;


import cn.itcast.domain.Person;
/**
 * 采用Pull解析XML内容
 */
public class PULLPersonService {
	
	public static void save(List<Person> persons, Writer writer) throws Throwable{
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(writer);
		serializer.startDocument("UTF-8", true);
		
		serializer.startTag(null, "persons");
		for(Person person : persons){
			serializer.startTag(null, "person");
			serializer.attribute(null, "id", person.getId().toString());
			
			serializer.startTag(null, "name");
			serializer.text(person.getName());
			serializer.endTag(null, "name");
			
			serializer.startTag(null, "age");
			serializer.text(person.getAge().toString());
			serializer.endTag(null, "age");
			
			serializer.endTag(null, "person");
		}
		serializer.endTag(null, "persons");		
		serializer.endDocument();
		writer.flush();
		writer.close();
	}
	
	public static List<Person> getPersons(InputStream inStream) throws Exception{
		List<Person> persons = null;
		Person person = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inStream, "UTF-8");
		int eventType = parser.getEventType();
		while(eventType!=XmlPullParser.END_DOCUMENT){
			switch(eventType){
			case XmlPullParser.START_DOCUMENT:
				persons = new ArrayList<Person>();
				break;
			case XmlPullParser.START_TAG:
				String name =parser.getName();//获取解析器当前指向的元素名称
				if("person".equals(name)){
					person=new Person();
					person.setId(new Integer(parser.getAttributeValue(0)));
					
				}
				if(person!=null){
					if("name".equals(name)){
						person.setName(parser.nextText());
					}else if("age".equals(name)){
						person.setAge(new Short(parser.nextText()));
					}
				}
				break;
			case XmlPullParser.END_TAG:
				if("person".equals(parser.getName())){
					persons.add(person);
					person=null;
				}
				break;
			}
			eventType=parser.next();
			
		}
		return persons;
	}
}



3、给出单元测试类

PersonServiceTest
必须继承AndroidTestCase类

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import cn.itcast.domain.Person;
import cn.itcast.service.DOMPersonService;
import cn.itcast.service.PULLPersonService;
import cn.itcast.service.SAXPersonService;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {
	private static final String TAG = "PersonServiceTest";

	public void testPullGetPersons() throws Throwable{
		InputStream inStream = getClass().getClassLoader().getResourceAsStream("jindegege.xml");
		List<Person> persons = PULLPersonService.getPersons(inStream);
		for(Person person : persons){
			Log.i(TAG, person.toString());
		}
	}
       public void testSave() throws Throwable{
		List<Person> persons = new ArrayList<Person>();
		persons.add(new Person(51, "liudehua", (short)12));
		persons.add(new Person(58, "成龙", (short)32));
		
		
		StringWriter writer = new StringWriter();
		PULLPersonService.save(persons, writer);
		Log.i(TAG, writer.toString());
	}
	
}




4、这里因为我们建立了单元测试类,所以需要在android manifest文件中添加 
<instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="com.cn" android:label="Tests for My App" />


给出代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cn"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
         <uses-library android:name="android.test.runner" />
        <activity android:name=".MainActivity"
                  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>
    <uses-sdk android:minSdkVersion="8" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="com.cn" android:label="Tests for My App" />
</manifest> 







   

你可能感兴趣的:(利用pull解析器解析xml文件)