java 如何将原始 XML 文本添加到 SOAPBody 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29944025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add raw XML text to SOAPBody element
提问by Evandro Pomatti
I have an XML text that is generated by the application, and I need to wrap a SOAP envelope around it and later make the web service call.
我有一个由应用程序生成的 XML 文本,我需要在它周围包裹一个 SOAP 信封,然后进行 Web 服务调用。
The following code builds up the envelope, but I don't know how the add the existing XML data into the SOAPBody
element.
以下代码构建了信封,但我不知道如何将现有的 XML 数据添加到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();
I have tried body.addTextNode()
but it adds content so <
and others get escaped.
我已经尝试过,body.addTextNode()
但它添加了内容,因此<
其他人逃脱了。
回答by Evandro Pomatti
The following adds the XML as a Document:
下面将 XML 添加为文档:
Document document = convertStringToDocument(rawXml);
body.addDocument(document);
Document creation:
文件创建:
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;
}
I took the convertStringToDocument()
logic from this post.
我convertStringToDocument()
从这篇文章中获取了逻辑。
回答by shazin
You need to tell the XML Serializer to not to parse and escape the SOAPBody
content as XML. You can do that by enclosing the XML inside <![CDATA[]]>
您需要告诉 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());
EDIT
编辑
<some-data><some-data-item>1</some-data-item></some-data>
This is the output of
这是输出
System.out.println(body.getTextContent());