经常在Http Post Xml请求的时候,需要如何拼装XML数据,在Android中如何来做的呢,通常我们使用FastXmlserializer这个类。比如要拼装如下的XML
Code
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Request xmlns="http://www.demo.com">
<operation>GetCustomerTariffInfo</operation>
<CustomerTariffInfoRequest>
<msisdn>44079324110</msisdn>
<detailsInfo>true</detailsInfo>
</CustomerTariffInfoRequest>
</Request>
代码如下
Code
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
XmlSerializer serializer = new FastXmlSerializer();
serializer.setOutput(out, "utf-8");
// true可以让stanalone为Yes.
serializer.startDocument("utf-8", true);
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "request");
//设置属性
serializer.attribute(null,"xmlns","http://www.demo.com");
serializer.text("\n");
serializer.startTag(null, "account");
serializer.text("");
serializer.endTag(null, "account");
serializer.startTag(null, "nickname");
serializer.text("");
serializer.endTag(null, "nickname");
serializer.startTag(null, "password");
serializer.text("");
serializer.endTag(null, "password");
serializer.endTag(null, "request");
serializer.endDocument();
out.flush();
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}