Android 生成 xml文件

利用 XmlSerializer写xml文件。
TestObject对象
private String AdID;
private String Name;
private String URL;

 public boolean createADXML(List<TestObject> data, String localDir) {
		boolean bFlag = false;
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		String strTmpName = sDateFormat.format(new java.util.Date()) + ".xml";
		FileOutputStream fileos = null;

		File newXmlFile = new File(localDir + strTmpName);
		try {
			if (newXmlFile.exists()) {
				bFlag = newXmlFile.delete();
			} else {
				bFlag = true;
			}

			if (bFlag) {

				if (newXmlFile.createNewFile()) {
					fileos = new FileOutputStream(newXmlFile);

					// we create a XmlSerializer in order to write xml data
					XmlSerializer serializer = Xml.newSerializer();

					// we set the FileOutputStream as output for the serializer,
					// using UTF-8 encoding
					serializer.setOutput(fileos, "UTF-8");

					// <?xml version=”1.0″ encoding=”UTF-8″>
					// Write <?xml declaration with encoding (if encoding not
					// null) and standalone flag (if stan dalone not null)
					// This method can only be called just after setOutput.
					serializer.startDocument("UTF-8", null);

					// start a tag called "root"
					serializer.startTag(null, "root");
					serializer.startTag(null, "Test");
					for (TestObject ad : data) {
						serializer.startTag(null, "TestObject");
						serializer.attribute(null, "ADID", ad.getId());
						serializer.attribute(null, "Name", ad.getName());
						serializer.attribute(null, "URL", ad.getUrl());
						serializer.endTag(null, "TestObject");						
					}
					serializer.endTag(null, "Test");
					serializer.endTag(null, "root");
					serializer.endDocument();

					// write xml data into the FileOutputStream
					serializer.flush();
					// finally we close the file stream
					fileos.close();
				}
			}
		} catch (Exception e) {
		}
		return bFlag;
	}



生成的XML文件:
<?xml version='1.0' encoding='UTF-8' ?>
<root>
<Test>
<TestObject ADID="9000001" Name="5325ad4" URL="http://www.xxx.com"  />
<TestObject ADID="9000002" Name="5325ad1" URL="http://www.xxx.com" />
<TestObject ADID="9000003" Name="5325ad3" URL="http://www.xxx.com" />
<TestObject ADID="9000004" Name="5325ad2" URL="http://www.xxx.com"  />
</Test>
</root>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值