使用pull解析xml和生成xml文件

前端之家收集整理的这篇文章主要介绍了使用pull解析xml和生成xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一:pull解析xml文件

1..布局文件

ctivity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
  <Button 
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text=”PULL解析XML"
    android:onClick="onClick"
  />
  <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </ListView>
</LinearLayout>


Person_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="姓名:" />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
     />
    <View 
        android:layout_width="25dp"
        android:layout_height="wrap_content"
     />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="年龄:" />
    <TextView
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
     />
</LinearLayout>

2.编写PullPersonService业务类,解析xml

package cn.com.service;

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

import org.apache.taglibs.standard.lang.jpath.example.Person;

public class PullPersonService {

	public static List<Person> getPerson(InputStream is) throws Exception {

		List<Person> persons = null;

		Person person = null;

		XmlPullParser pullParser = Xml.newPullParser();// 实例化pull解析器

		pullParser.setInput(is,"utf-8");// 为pull解析器设置要解析的xml数据

		int event = pullParser.getEventType();// 产生第一个事件

		while (event != XmlPullParser.END_DOCUMENT) {

			switch (event) {

			case XmlPullParser.START_DOCUMENT:// 判断当前事件是否是文档开始事件

				persons = new ArrayList<Person>();

				break;

			case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件

				if ("person".equals(pullParser.getName())) {

					int id = Integer.valueOf(pullParser.getAttributeValue(0));

					person = new Person();

					person.setId(id);

				}

				if (person != null) {

					if ("name".equals(pullParser.getName())) {

						person.setName(pullParser.nextText());

					}

					if ("age".equals(pullParser.getName())) {

						person.setAge(Integer.valueOf(pullParser.nextText()));

					}

				}

				break;

			case XmlPullParser.END_TAG:// 判断当前事件是否是标签元素结束事件

				if ("person".equals(pullParser.getName())) {

					persons.add(person);

					person = null;

					break;

				}

			}

			event = pullParser.next();// 进入下一个元素并触发相应事件

		}

		return persons;

	}

}


3.测试类

package com.example.pull;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import cn.com.entity.Person;

import cn.com.service.PullPersonService;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.ListView;

import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

	private ListView listView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		listView = (ListView) findViewById(R.id.listView1);

	}

	public void onClick(View view) throws Exception {

		List<Person> persons = readXml();

		List<Map<String,String>> data = new ArrayList<Map<String,String>>();

		for (Person person : persons) {

			Map<String,String> map = new HashMap<String,String>();

			map.put("name",person.getName());

			map.put("age","" + person.getAge());

			data.add(map);

		}

		SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,data,R.layout.person_main,new String[] { "name","age" },new int[] { R.id.name,R.id.age });

		listView.setAdapter(adapter);

	}

	public List<Person> readXml() throws Exception {

		// 加载需要解析的文件。因为XML文件放在src目录下,所以通过类装载器的方式获得文件路径,再以输入流的方式放入解析器

		InputStream inputStream = this.getClass().getClassLoader()

		.getResourceAsStream("person.xml");

		List<Person> persons = PullPersonService.getPerson(inputStream);

		return persons;

	}

}







二:pull生成xml文件的序列化)

1.编写一个CreateXML业务类,序列化生成xml文件

package cn.com.service;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.os.Environment;

import android.util.Log;

import android.util.Xml;

import cn.com.entity.Person;

public class CreateXML {

	public static void save(List<Person> persons) throws Exception {

		XmlSerializer serializer = Xml.newSerializer();// 实例化一个序列化

		// 创建保存xml文件路径

		File file = new File(Environment.getExternalStorageDirectory(),"person.xml");

		FileOutputStream os = new FileOutputStream(file);

		Log.i("TAG",file.toString());

		serializer.setOutput(os,"utf-8");// 初始化序列化器,指定xml写入到那个文件,并指定文件编码

		serializer.startDocument("utf-8",true);// xml头信息 <?xml version="1.0"
												// encoding="UTF-8"?>

		// 命名 如:xmlns:android="http://schemas.android.com/apk/res/android"

		// 这里设置命名空间为空

		serializer.startTag(null,"persons");// 开始标签 <persons>

		for (Person p : persons) {

			serializer.startTag(null,"person"); // <person>

			serializer.attribute(null,"id",p.getId() + ""); // <person id="a">
																// 设置属性

			// <name>aa</name>

			serializer.startTag(null,"name");

			serializer.text(p.getName());

			serializer.endTag(null,"name");

			// <age>aa</age>

			serializer.startTag(null,"name");

			serializer.text(p.getAge() + "");

			serializer.endTag(null,"name");

			serializer.endTag(null,"person");// </person>

		}

		serializer.endTag(null,"persons");// 结束标签 </persons>

		serializer.endDocument();// xml结束

	}

}


2.创建一个测试类PullTest.java

package com.example.pull;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import cn.com.entity.Person;

import cn.com.service.CreateXML;

import cn.com.service.PullPersonService;

import android.test.AndroidTestCase;

import android.util.Log;

public class PullTest extends AndroidTestCase {

	public void testSave() throws Exception {

		List<Person> persons = new ArrayList<Person>();

		persons.add(new Person(12,"张三",23));

		persons.add(new Person(14,"李四",32));

		persons.add(new Person(16,"王伟",34));

		persons.add(new Person(32,"张瑟",56));

		CreateXML.save(persons);

	}

}


3.记得在配置文件添加权限

<user-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

执行后,生成xml存放在


生成person.xml如下

原文链接:https://www.f2er.com/xml/299602.html

猜你在找的XML相关文章