Java 如何将JAXBElement作为SOAPBody的子级附加到SOAP消息中

Java 如何将JAXBElement作为SOAPBody的子级附加到SOAP消息中,java,soap,jaxb,spring-ws,Java,Soap,Jaxb,Spring Ws,如何将JAXBElement作为SOAPBody的子级附加到SOAP消息。我在web服务端点方法中尝试做的是: SaajSoapMessage soapRequest = (SaajSoapMessage) messageContext.getRequest(); SOAPBody soapBody=soapRequest.getSaajMessage().getSOAPBody(); ObjectFactory of=new ObjectFactory(); S

如何将JAXBElement作为SOAPBody的子级附加到SOAP消息。我在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);
SaajSoapMessage soapRequest=(SaajSoapMessage)messageContext.getRequest();
SOAPBody SOAPBody=soapRequest.getSaajMessage().getSOAPBody();
ObjectFactory of=新的ObjectFactory();
SplsTID tid=新的SplsTID();
JAXBElement元素=of.createSplsTID(tid);
元素soapBody.appendChild(元素);
然后我得到
java.lang.ClassCastException:javax.xml.bind.JAXBElement不能转换为org.w3c.dom.Element


我正在使用SpringWS并使用jaxb marshaller。我们怎么能做到这一点呢?

基本上,你必须越过你的肩膀去抓你的屁股

使用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;

还有一个选择。使用XmlBeans来构建类(这将使使用JAXB变得困难,从而导致JAX-WS)。

我认为我提出了一个稍微优雅一点的解决方案:

// 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();

在哪一行抛出异常?向我们展示完整的堆栈跟踪,而不仅仅是其中的一位其中
元素
的类型为
JAXBElement
。下面是堆栈跟踪:
java.lang.ClassCastException:javax.xml.bind.JAXBElement不能强制转换为com.staples.onas.util.ONASUtil.createPublishLog(ONASUtil.java:158)com.staples.onas.service.endpoint.OrderNumberServiceEndPoint.processOrderNumberRequest(OrderNumberServiceEndPoint.java:73)上的org.w3c.dom.dom.dom.dom.Element在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
。由于大小限制,我无法在此处粘贴完整堆栈跟踪。如果需要更多细节,请告诉我。