(Android review)XML的解析与序列化


这篇博客主要用来介绍对XML文件的操作:解析与生成。


Android手机内部的解析就是pull解析
官网:http://xmlpull.org/
所谓的解析,我们可以理解为:利用XML文件的内容来生成一个对象
导出生成的xml文件后不要对其格式化,否则会出异常


1、MainActivity

package com.example.xmlparsertest1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@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;
	}

}


2、Person

package com.example.xmlparsertest1;

public class Person {

	private Integer id;
	private String name;
	private Integer age;
	
	
	public Person() {
		// TODO Auto-generated constructor stub
	}
	
	
	
	public Person(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}



	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}



	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
	
}


3、PersonService

package com.example.xmlparsertest1;

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

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

import android.util.Xml;

public class PersonService {

	/**
	 * 解析XML文件
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public List<Person> loadPersons(InputStream in) throws Exception{
		XmlPullParser parser = Xml.newPullParser();//获取解析器
		parser.setInput(in,"UTF-8");//指定输入流、码表
		
		ArrayList<Person> persons = new ArrayList<Person>();
		Person p = null;
		
		/**
		 * parser.getName():获取标签的名字
		 * parser.getAttributeValue(0): 获取某个属性的值
		 * parser.next(): 让指针指向下一个标签
		 * parser.nextText(): 获取某个标签的文本内容
		 */
		for(int type = parser.getEventType() ; type != XmlPullParser.END_DOCUMENT ; type = parser.next()){
			if(type == XmlPullParser.START_TAG){
				if(parser.getName().equals("person")){
					p = new Person();
					String id = parser.getAttributeValue(0);//获取该标签的第0个属性的值(value)
//					String id = parser.getAttributeValue(null, "id");//这样写也行。第一个参数是命名空间,第二个参数是属性的名字
					p.setId(Integer.parseInt(id));
					persons.add(p);
				}else if(parser.getName().equals("name")){
					String name = parser.nextText();
					p.setName(name);
				}else if(parser.getName().equals("age")){
					String age = parser.nextText();
					p.setAge(Integer.parseInt(age));
				}
			}
		}
		
		return persons;
	}
	//生成XML文件
	public void savePersons(List<Person> persons,OutputStream out)throws Exception{
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(out,"UTF-8");
		
		serializer.startDocument("UTF-8", true);//开始文档
		serializer.startTag(null, "persons");//开始标签
		
		/**
		 * serializer.startDocument("UTF-8", true);//开始文档
		 * serializer.startTag(null, "persons");//开始标签
		 * serializer.attribute(null, "id", p.getId().toString());//设置属性
		 * serializer.text(p.getName());//设置标签的文本内容
		 * serializer.endTag(null, "persons");
		 * serializer.endDocument();
		 */
		for(Person p : persons){
			serializer.startTag(null, "person");
			serializer.attribute(null, "id", p.getId().toString());//设置属性
			
			serializer.startTag(null, "name");
			serializer.text(p.getName());//设置标签的文本内容
			serializer.endTag(null, "name");
			
			serializer.startTag(null, "age");
			serializer.text(p.getAge().toString());
			serializer.endTag(null, "age");
			
			serializer.endTag(null, "person");
		}
		
		serializer.endTag(null, "persons");
		serializer.endDocument();
	}
}


4、PersonServiceTest

package com.example.xmlparsertest1;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import android.os.Environment;
import android.test.AndroidTestCase;

public class PersonServiceTest extends AndroidTestCase {

	public void testXMLParser() throws Exception{
		PersonService service = new PersonService();
		//获取src目录下的资源为输入流方法
		InputStream in = PersonServiceTest.class.getClassLoader().getResourceAsStream("persons_hjd.xml");
		List<Person> persons = service.loadPersons(in);
		
		
		for(Person p : persons){
			System.out.println( "----------->" + p);
		}
		
		
//		Person p = new Person(4, "hjd", 22);
//		persons.add(p);
//		
//		service.savePersons(persons, new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + "persons_hjd.xml"));
	}
	
}


以下附上需要解析的XML文件:persons.xml

<?xml version=‘1.0‘ encoding=‘UTF-8‘ standalone=‘yes‘ ?>
<persons>
	<person id="1">
		<name>范冰冰</name>
		<age>31</age>
	</person>
	<person id="2">
		<name>林志玲</name>
		<age>38</age>
	</person>
	<person id="3">
		<name>杨幂</name>
		<age>26</age>
	</person>
</persons>



源码下载:http://download.csdn.net/detail/caihongshijie6/7616863



(Android review)XML的解析与序列化,布布扣,bubuko.com

(Android review)XML的解析与序列化

上一篇:SVN Upgrade working copy


下一篇:ios UIWebView 加载网页、文件、 html