写xml文件

package com.example.day_18_bean2xml;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import org.xmlpull.v1.XmlSerializer;


import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Person> list = new ArrayList<Person>();


for (int i = 0; i < 3; i++) {
Person person = new Person("宽叔" + i, i + "");
list.add(person);
}


XmlSerializer newSerializer = Xml.newSerializer();


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


FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file,false);
// 设置输出流
newSerializer.setOutput(fileOutputStream, "utf-8");
// 文档开始,设置编码集,是否依赖外部DTD约束
newSerializer.startDocument("utf-8", false);
// 设置第一个开始标签,设置开始标签名
newSerializer.startTag(null, "persons");


for (int j = 0; j < list.size(); j++) {
// 开始标签person
newSerializer.startTag(null, "person");
// 开始标签name
newSerializer.startTag(null, "name");
// 设置标签的文本
newSerializer.text(list.get(j).name);
// 结束标签name
newSerializer.endTag(null, "name");


// 开始标签age
newSerializer.startTag(null, "age");
// 设置标签的文本
newSerializer.text(list.get(j).age);
// 结束标签age
newSerializer.endTag(null, "age");
// 结束标签person
newSerializer.endTag(null, "person");


}
// 文档已经结束
newSerializer.endDocument();


} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}

======================================================================================

/**
 * 
 */
package com.example.day_18_bean2xml;


/**
 * @author WJL
 * 
 */
public class Person {


public Person(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String name;
public String age;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值