欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-01 19:12:28
本文实例讲述了android中常用的xml生成方法。分享给大家供大家参考。具体如下: 1. java代码: package com.android.antkin...

本文实例讲述了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程序设计有所帮助。