利用 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>