生成xml文件

<span style="font-size:14px;">package com.lrk.login.makexml;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;

import org.kxml2.io.KXmlSerializer;
import org.xmlpull.v1.XmlSerializer;

import sun.util.logging.resources.logging;

import com.lrk.login.person.Person;

/**
 * 作用:通过XmlSerializer构造器生成xml数据结构
 * 传给客户端
 * @author kevin
 *
 */
public class PullMakeXML {
	
	private ArrayList<Person> mListperson;
	private StringWriter mWriter;

	public PullMakeXML(ArrayList<Person> mListperson, StringWriter mWriter) {
		this.mListperson = mListperson;
		this.mWriter = mWriter;
	}

	public String makeXML(){
		//获得一个pull的xml 构造器
		XmlSerializer serializer = new KXmlSerializer();
		try {
			// 生成的这个xml文件放到writer输出流里面去
			serializer.setOutput(mWriter);
			
			//开始写xml文件
			serializer.startDocument("UTF-8", true);
			
			//第一个参数为命名空间,如果不使用命名空间,可以设置为null
			serializer.startTag("", "person");
			for(Person p: mListperson){
				//写第一对象
				serializer.startTag("", "person");
				//写这个对象的属性id的头标签
				serializer.startTag("", "id");
				//写这个对象的属性值
				serializer.text(String.valueOf(p.getId()));
				//写这个对象的属性id的结尾标签
				serializer.endTag("", "id");
				
				serializer.startTag("", "name");
				serializer.text(p.getName());
				serializer.endTag("", "name");
				
				serializer.startTag("", "password");
				serializer.text(p.getPassword());
				serializer.endTag("", "password");
				
				serializer.endTag("", "person");
			}
			
			serializer.endTag("", "person");
			serializer.endDocument();
			
			
		} catch (IllegalArgumentException e) {
			System.out.println("PullMakeXML-makeXML异常");
			e.printStackTrace();
		} catch (IllegalStateException e) {
			System.out.println("PullMakeXML-makeXML异常");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("PullMakeXML-makeXML异常");
			e.printStackTrace();
		}
		
		return mWriter.toString();
	}
}
</span>


你可能感兴趣的:(生成xml文件)