Android开发

Android中常用的XML生成方法实例分析

本文主要是介绍Android中常用的XML生成方法实例分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文实例讲述了Android中常用的XML生成方法。分享给大家供大家参考。具体如下:

1. java代码:

package com.android.antking.xml;
import java.io.OutputStream;
import java.util.List;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
/**采用pull 生成xml文件
 * 
 * @author antkingwei
 *
 */
public class PullBuildXMLService {
 public void buildXML(List<Person> persons,OutputStream outputStream)throws Exception{
  XmlSerializer serializer = Xml.newSerializer();
  serializer.setOutput(outputStream,"utf-8");
  serializer.startDocument("utf-8", true);
  serializer.startTag(null, "perisons");
  for(Person person:persons){
   serializer.startTag(null, "perison");
   serializer.attribute(null, "id",String.valueOf(person.id));
   serializer.startTag(null, "name");
   serializer.text(person.name);
   serializer.endTag(null, "name");
   serializer.startTag(null, "age");
   serializer.text(String.valueOf(person.age));
   serializer.endTag(null, "age");
   serializer.endTag(null, "perison");
  }
  serializer.endTag(null, "perisons");
  serializer.endDocument();
  outputStream.close();
 }
}

2. java ben:

package com.android.antking.xml;
public class Person {
  public int id;
  public String name;
  public int age;
}

3. 调用方法:

public void writeFile() throws Throwable{
  List<Person> list = new ArrayList<Person>();
  for(int i =0;i<10;i++){
   Person person = new Person();
   person.id = 1;
   person.name = "ant";
   person.age = 12;
   list.add(person);
  }
  File file = new File(MainActivity.this.getFilesDir(),"person.xml");
  FileOutputStream outputStream = new FileOutputStream(file);
  PullBuildXMLService service = new PullBuildXMLService();
  service.buildXML(list, outputStream);
}

希望本文所述对大家的Android程序设计有所帮助。

这篇关于Android中常用的XML生成方法实例分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!