通过Pull解析器生成xml文件

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

通过Pull解析器生成xml文件代码

public static void save(OutputStream outStream) throws Exception{
		//生成模拟数据
		List<Person> persons = new ArrayList<Person>();
		persons.add(new Person(90,"liming",(short)29));
		persons.add(new Person(30,"laozhu",(short)33));
		persons.add(new Person(45,"linsan",(short)57));
		
		//生成XmlSerializer
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(outStream,"UTF-8");
		
		//xml文件开头,有开始必有结束
		serializer.startDocument("UTF-8",true);
		
		//xml文件节点的开头,同时有结束
		serializer.startTag(null,"persons");
		
		//递归,生成xml文件的各个元素
		for(Person person : persons){
			serializer.startTag(null,"person");
			serializer.attribute(null,"id",person.getId().toString());
			
			//生成xml文件的元素参数
			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");
		
		//xml文件结束标志
		serializer.endDocument();
		
		if(outStream != null){
			outStream.close();
		}
	}


生成后的xml文件形式:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<persons>
    <person id="90">
        <name>liming</name>
        <age>29</age>
    </person>
    <person id="30">
        <name>laozhu</name>
        <age>33</age>
    </person>
    <person id="45">
        <name>linsan</name>
        <age>57</age>
    </person>
</persons>

猜你在找的XML相关文章