我正在使用 JAX-WS 服务。以下是请求类的部分内容。
@XmlElement(name = "Answers")
protected String answers;
现在,在实际的 SOAP 请求中,答案需要在 xml 中作为 CDATA 发送。有一个单独的 stub 类用于答案。因此,我将该类的对象编码到一个 xml 中。我在 CDATA 标签中围绕着它,如下所示:
xmlstr = "<![CDATA[" + xmlstr + "]]>";
因此,我的请求 xml 应该如下所示:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<!-- Other tags -->
<Answers>
<![CDATA[
<TagOne></TagOne>
<TagTwo></TagTwo>
]]>
</Answers>
</S:Body>
</S:Envelope>
但是,当请求从 SOAPLoggingHandler 发送到服务器时,它看起来像这样:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<!-- Other tags -->
<Answers>
<![CDATA[
<TagOne></TagOne>
<TagTwo></TagTwo>
]]>
</Answers>
</S:Body>
</S:Envelope>
由于这种字符转义,我收到了“无效的答案 xml 格式”的回复。我有两个问题:
xmlstr = ""是从 bean 创建 CDATA xml 的正确方法吗?如果没有,是否有任何标准方法可以做到这一点?
如果我想在不转义的情况下发送请求中的 CDATA 部分,我应该对我的实现进行哪些更改?
如果还有其他需要,请告诉我。
最佳答案
我认为这里的情况是您的 java 对象表示与您希望在 XML 中看到的不完全匹配。并假设您将 JAXB 与 JAX-WS 结合使用,然后您可以使用 XmlJavaTypeAdapter 注释为 bean 中的元素创建一个适配器类。
public class CDATAAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String v) throws Exception {
return "<![CDATA[" + v + "]]>";
}
@Override
public String unmarshal(String v) throws Exception {
return v;
}
}
在你的bean中:
@XmlElement(name = "Answers")
@XmlJavaTypeAdapter(value=CDATAAdapter.class)
protected String answers;
关于java - SOAP 请求 XML 中的 CDATA 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21596080/