使用Pull解析器生成XML文件和读取xml文件

有些时候,我们需要生成一个XML文件,生成XML文件的方法有很多,如:可以只使用一个StringBuilder组拼XML内容,然后把内容写入到文件中;或者使用DOM API生成XML文件,或者也可以使用pull解析器生成XML文件,这里推荐大家使用Pull解析器。

一、布局界面

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_pull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="110dp"
        android:text="@string/btn_pull" />

    <Button
        android:id="@+id/btn_write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_pull"
        android:layout_alignRight="@+id/btn_pull"
        android:layout_below="@+id/btn_pull"
        android:layout_marginTop="61dp"
        android:text="@string/btn_write" />

</RelativeLayout>


使用Pull解析器生成XML文件和读取xml文件_第1张图片

二、写一个xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id="23">
		<name>李明</name>
		<age>30</age>
	</person>
	<person id="20">
		<name>李向梅</name>
		<age>25</age>
	</person>
</persons>


三、写一个和xml相对应的bean

package com.example.lession04_pull.domain;

import java.io.Serializable;

public class Person implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private short age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public short getAge() {
		return age;
	}
	public void setAge(short age) {
		this.age = age;
	}
	public Person(int id, String name, short age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
}


四、写一个Pul的服务类

package com.example.lession04_pull.service;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.os.Environment;
import android.util.Xml;

import com.example.lession04_pull.domain.Person;

public class PullXmlService {
	
	public Person currentPerson;

	public List<Person> readXml(InputStream is){
		//声明返回值
		List<Person> persons=null;
		//首先利用Xml.newPullParser()获取解析对象
		XmlPullParser xmlPullParser=Xml.newPullParser();
		try{
			// 解析文件
			xmlPullParser.setInput(is, "UTF-8");
			//获取解析的事件类型
			int eventType=xmlPullParser.getEventType();
			//判断文件解析的是否完毕
			while(eventType!=XmlPullParser.END_DOCUMENT){
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					persons=new ArrayList<Person>();
					break;

				case XmlPullParser.START_TAG:
					String tagName=xmlPullParser.getName();
					if("person".equals(tagName)){
						//创建person对象
						currentPerson=new Person();
						currentPerson.setId(Integer.parseInt(xmlPullParser
								.getAttributeValue(null, "id")));
					}else if("name".equals(tagName)){
						currentPerson.setName(xmlPullParser.nextText());
					}else if("age".equals(tagName)){
						currentPerson.setAge(new Short(xmlPullParser.nextText()));
					}
					break;
				case XmlPullParser.END_TAG:
					if("person".equals(xmlPullParser.getName()) && currentPerson!=null){
						//把person对象放到集合中去
						persons.add(currentPerson);
						currentPerson=null;
					}
					break;
				}
				eventType=xmlPullParser.next();
			}
			is.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return persons;
	}
	
	
	
	// 写入
		public boolean write(List<Person> persons) {
			// 采用pull解析进行实现

			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {

				// 获取sdcard目录 文件对象
				File sdCardDir = Environment.getExternalStorageDirectory();
				// 创建文件
				File file = new File(sdCardDir, "mycsdn.xml");

				XmlSerializer serializer = Xml.newSerializer();

				FileOutputStream fos = null;
				try {
					// 根据文件对象创建一个文件的输出流对象
					fos = new FileOutputStream(file);
					// 设置输出的流及编码
					serializer.setOutput(fos, "UTF-8");
					// 设置文件的开始
					serializer.startDocument("UTF-8", true);
					// persons标签开始
					serializer.startTag(null, "persons");
					for (Person person : persons) {
						// person标签的开始
						serializer.startTag(null, "person");
						// 设置person标签的属性
						serializer.attribute("null", "id", person.getId() + "");

						// 设置person标签的子标签 name
						serializer.startTag(null, "name");
						serializer.text(person.getName());
						serializer.endTag(null, "name");

						// 设置person标签的子标签的age
						serializer.startTag(null, "age");
						serializer.text(person.getAge() + "");
						serializer.endTag(null, "age");

						// person标签的结束
						serializer.endTag(null, "person");
					}

					// persons标签的结束
					serializer.endTag(null, "persons");
					// 文件的结束
					serializer.endDocument();

					fos.flush();
					fos.close();
					return true;
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			return false;
		}

}


五、在MainActivity中调用测试

package com.example.lession04_pull;

import java.util.List;

import com.example.lession04_pull.domain.Person;
import com.example.lession04_pull.service.PullXmlService;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	public Button btn_pull,btn_write;
	public PullXmlService pullXmlService;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//实例化
		pullXmlService=new PullXmlService();
		
		btn_pull=(Button) findViewById(R.id.btn_pull);
		btn_write=(Button) findViewById(R.id.btn_write);
		
		btn_pull.setOnClickListener(new MyOnClickListener());
		btn_write.setOnClickListener(new MyOnClickListener());
	}

	@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;
	}
	
	class MyOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			int id=v.getId();
			switch (id) {
			case R.id.btn_pull:
				List<Person> persons=null;
				try{
					persons=pullXmlService.readXml(getAssets().open("csdn.xml"));
				}catch(Exception e){
					e.printStackTrace();
				}
				if(persons!=null){
					Toast.makeText(MainActivity.this, "采用pull解析xml文件"+persons.get(0).getName()+"--"+persons.get(1).getName(),
							Toast.LENGTH_LONG).show();
				}
				break;

			case R.id.btn_write:
				try{
					List<Person> pers=pullXmlService.readXml(getAssets().open("csdn.xml"));
					//重新生成一个xml文件  mysdcare.xml
					boolean flag=pullXmlService.write(pers);
					if(flag){
						Toast.makeText(MainActivity.this, "采用pull解析生产xml文件成功",
								Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(MainActivity.this, "采用pull解析生产xml文件失败",
								Toast.LENGTH_LONG).show();
						
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				break;
			}
			
		}
		
	}

}



 

你可能感兴趣的:(使用Pull解析器生成XML文件和读取xml文件)