码迷,mamicode.com
首页 > 其他好文 > 详细

用序列化工具写入xml

时间:2015-10-19 18:51:35      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

标本:

<?xml version="1.0" encoding="UTF-8" standalone="true"?> //文档的申明
<persons> //标签tag
   <person id=“18"> //ID是person标签的一个属性
      <name>allen</name>
      <age>36</age>
   </person>
   <person id=“28">
      <name>james</name>
      <age>25</age>
   </person>
</persons>

代码:

1、获取xml序列化工具以及要存放的路径设定
XmlSerializer serializer = Xml.newSerializer();
File path = new File(Environment.getExternalStorageDirectory(), "persons.xml");
try {
FileOutputStream out = new FileOutputStream(path);
serializer.setOutput(out, "utf-8");// 给序列化工具设置输出路径和编码集
2、准备序列化的内容

//文档的申明开始----encoding="UTF-8"  standalone="true"
serializer.startDocument("utf-8", true);
//开始persons标签-----<persons>
serializer.startTag(null, "persons");// namespace命名空间,一般为null,name代表的是标签名
//开始person标签-----<person>
serializer.startTag(null, "person"); 
serializer.attribute(null, "id", "18");// 用来指定标签属性-----id=“18"
// 构建name标签-----<name>
serializer.startTag(null, "name");
serializer.text("张三");// -----设置一个name标签的内容
serializer.endTag(null, "name");// -----</name>
// 构建age标签 -----<age>
serializer.startTag(null, "age");
serializer.text("18");// -----设置一个age标签的内容
serializer.endTag(null, "age");// -----</age>

serializer.endTag(null, "person");// 对应的person标签结束-----</person>
serializer.endTag(null, "persons");// 对应的persons标签结束-----</persons>
serializer.endDocument();// 文档申明结束
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

用序列化工具写入xml

标签:

原文地址:http://www.cnblogs.com/zzw1994/p/4892319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!