昨天我们做了XML文件的内容解析,但我们有时候和服务器交互的时候需要生成json(讲解完XML后就讲解json的解析和生成)或者XML格式的数据。于是就有了生成XML格式数据的需求。
生成XML数据有很多种方式,最笨的方法就是一个一个去拼接,然后通过IO流写入文件,当然这非常的麻烦。因为博主搞的是安卓开发,常用的就是Android自带的XmlSerializer来生成XML文件内容。
形成的参考文件和昨天内容一样:
<?xml version='1.0' encoding='UTF-8' ?>
<菜系>
<span style="white-space:pre"> </span><菜 id="1">
<span style="white-space:pre"> </span><菜名>饭炒蛋</菜名>
<span style="white-space:pre"> </span><图片路径>d:\pic</图片路径>
<span style="white-space:pre"> </span> <售价>10.0元</售价>
<span style="white-space:pre"> </span></菜>
<span style="white-space:pre"> </span><菜 id="2">
<span style="white-space:pre"> </span><菜名>蛋炒饭</菜名>
<span style="white-space:pre"> </span><图片路径>d:\pic</图片路径>
<span style="white-space:pre"> </span><售价>10.0元</售价>
<span style="white-space:pre"> </span>></菜>
</菜系>
首先,一般来说,XML数据格式包括一个标签名和标签值,所以博主定义了一个product类(这里只做最底层的标签,只用作参考说明,在实际开发中可以将所有标签都做成一个类,便于管理,也使代码能够整洁规范。在这里也没有加入attribute,有兴趣的同学可以将这个类做的更完善,加入attribute属性值)
public class Product {
private String tagName;
private String tagValue;
public Product(String tagName, String tagValue) {
super();
this.tagName = tagName;
this.tagValue = tagValue;
}
public Product(String tagName) {
super();
this.tagName = tagName;
}
public String getTagValue() {
return tagValue;
}
public void setTagValue(String tagValue) {
this.tagValue = tagValue;
}
public String getTagName() {
return tagName;
}
/**
* 序列化节点
*
* @param serializer
*/
public void serializerLeaf(XmlSerializer serializer) {
try {
serializer.startTag(null, tagName);
if (StringUtils.isBlank(tagValue)) {
tagValue = "";
}
serializer.text(tagValue);
serializer.endTag(null, tagName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
接下来是生成XML数据代码
1、生成所有子节点
private void serizlizerProductCategory(XmlSerializer serializer)
throws IOException {
for (int i = 1; i <= 2; i++) {
serializer.startTag(null, "菜");
serializer.attribute("", "id", i + "");
// leaf
if (i == 1) {
Product product = new Product("菜名", "饭炒蛋");
Product product1 = new Product("图片路径", "d:\\pic");
Product product2 = new Product("售价", "10.0元");
product.serializerLeaf(serializer);
product1.serializerLeaf(serializer);
product2.serializerLeaf(serializer);
} else if (i == 2) {
Product product = new Product("菜名", "蛋炒饭");
Product product1 = new Product("图片路径", "d:\\pic");
Product product2 = new Product("售价", "10.0元");
product.serializerLeaf(serializer);
product1.serializerLeaf(serializer);
product2.serializerLeaf(serializer);
}
serializer.endTag(null, "菜");
}
}
2、生成根节点及整个文件内容
public void creatProductXml() {
XmlSerializer serializer = Xml.newSerializer();
try {
StringWriter writer = new StringWriter();
serializer.setOutput(writer);
/**
* 这个方法必须在setOutput之后。
*/
serializer.startDocument("UTF-8", null);
serializer.startTag(null, "菜系");
serizlizerProductCategory(serializer);
serializer.endTag(null, "菜系");
serializer.endDocument();
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
最后从logcat中可以看到打印出来的内容和上面的XML文档内容一样。至此,只需要通过IO生成一个.xml文件,将内容写进去即可。文件IO流的读写在后续的文章会再详细讲到,这里不再描述。