如何将原始XML文本添加到SOAPBody元素

时间:2015-04-29 12:40:00

标签: java xml

我有一个由应用程序生成的XML文本,我需要在其周围包装一个SOAP信封,然后再调用Web服务。

以下代码构建了信封,但我不知道如何将现有XML数据添加到SELECT id, sum(value) as value FROM ( SELECT id, v1 as value from article UNION ALL SELECT articleID, v2 from article_details )articleUnion GROUP BY id 元素中。

SOAPBody

我已尝试 String rawXml = "<some-data><some-data-item>1</some-data-item></some-data>"; // Start the API MessageFactory mf = MessageFactory.newInstance(); SOAPMessage request = mf.createMessage(); SOAPPart part = request.getSOAPPart(); SOAPEnvelope env = part.getEnvelope(); // Get the body. How do I add the raw xml directly into the body? SOAPBody body = env.getBody(); ,但它添加的内容为body.addTextNode(),其他内容则被转义。

2 个答案:

答案 0 :(得分:8)

以下将XML添加为文档:

Document document = convertStringToDocument(rawXml);
body.addDocument(document);

文档创建:

private static Document convertStringToDocument(String xmlStr) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

我从this post获取convertStringToDocument()逻辑。

答案 1 :(得分:-1)

您需要告诉XML Serializer不要将SOAPBody内容解析为XML并将其转义。您可以通过将XML括在<![CDATA[]]>

中来实现
    String rawXml = "<![CDATA[<some-data><some-data-item>1</some-data-item></some-data>]]>";

    // Start the API
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage request = mf.createMessage();
    SOAPPart part = request.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();

    // Get the body. How do I add the raw xml directly into the body?
    SOAPBody body = env.getBody();

    SOAPElement se = body.addTextNode(rawXml);

    System.out.println(body.getTextContent());

修改

<some-data><some-data-item>1</some-data-item></some-data>

这是

的输出
System.out.println(body.getTextContent());