Vis*_*ari 2 java soap spring-ws jaxb
如何将JAXBElement作为SOAP消息的SOAPBody的子项追加.我在我的Web服务端点方法中尝试做的是:
SaajSoapMessage soapRequest = (SaajSoapMessage) messageContext.getRequest();
SOAPBody soapBody=soapRequest.getSaajMessage().getSOAPBody();
ObjectFactory of=new ObjectFactory();
SplsTID tid=new SplsTID();
JAXBElement<SplsTID> element=of.createSplsTID(tid);
element.soapBody.appendChild(element);
Run Code Online (Sandbox Code Playgroud)
然后我得到了java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to org.w3c.dom.Element.
我正在使用spring-WS并使用jaxb marshaller.我们应该怎么做?
我想我想出了一个更优雅的解决方案:
// Having a SOAPMessage message and a JAXBContext context...
// Marshall the JAXB object request into to a DOM document
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Marshaller marshaller = context.createMarshaller();
marshaller.marshal(request,document);
// Finally attach the document to the message and save. Done!
soapBody.addDocument(document);
message.saveChanges();
Run Code Online (Sandbox Code Playgroud)
基本上,你必须越过你的肩膀挠你的屁股。
使用 JAXBContext 创建编组器,将其全部转换为字符串。然后将字符串转换为 xml 元素。
private static Element JAXBElementToDomElement(MyClassThatImTryingToConvert element) {
try {
JAXBContext jc = JAXBContext.newInstance(new Class[] {
MyClassThatImTryingToConvert.class, OtherJAXBClasses.class });
Marshaller um = jc.createMarshaller();
StringWriter sw = new StringWriter();
um.marshal(element, sw);
InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
return xmlDocument.getDocumentElement();
} catch (Exception ex) {
log.log(Level.FATAL, "can't create dom element", ex);
}
return null;
Run Code Online (Sandbox Code Playgroud)
还有一种选择。使用 XmlBeans 构建您的类(这将使使用 JAXB 变得困难,因此使用 JAX-WS)。
| 归档时间: |
|
| 查看次数: |
8595 次 |
| 最近记录: |