2

我通过构建输入并作为请求发送SOAP从 android调用 .net Web 服务。XML接收作为XML字符串响应并解析它。以上所有工作正常。

为了构建 XML 字符串,我遵循使用这样的DocumentBuilderFactory示例的方法

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();

Element rootElement = document.createElement("XMLINPUT");//Parent Node of the xml
document.appendChild(rootElement);

Element childElementCNN = document.createElement("CNNREFF");//Child Node
rootElement.appendChild(childElementCNN);
childElementCNN .appendChild(document.createTextNode(strCNN));

Element childElementCTT = document.createElement("CTTREFF");//Child Node
rootElement.appendChild(childElementCTT);
childElementCTT.appendChild(document.createTextNode(strCTT));

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Properties outFormat = new Properties();
outFormat.setProperty(OutputKeys.INDENT, "yes");
outFormat.setProperty(OutputKeys.METHOD, "xml");
outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
outFormat.setProperty(OutputKeys.VERSION, "1.0");
outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperties(outFormat);
DOMSource domSource = new DOMSource(document.getDocumentElement());
OutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(domSource, result);
String strInputXML = output.toString(); //Storing into a string

我想知道在 android 中构建 XML,因为我想使用相同的函数来构建不同的 XML。还有其他替代解决方案吗?如果有,请发布您的答案。

4

1 回答 1

2

是的,看看SimpleXML

您可以根据您的 XML 文档结构定义 bean,并使用 getter/setter 来操作值。

@Root(name = "XMLINPUT")
class MyBean {

    @Element(name = "CNNREFF")
    private String child1;

    @Element(name = "CTTREFF")
    private String child2;


}
于 2012-12-18T10:20:38.640 回答