2011-12-27 111 views
2

如何將JAXBElement作爲SOAP消息的SOAPBody的子節點追加。我想做我的Web服務端點方法裏面做的是:如何將JAXBElement作爲SOAP消息的子節點附加到SOAP消息

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

然後我得到的java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to org.w3c.dom.Element

我正在使用spring-WS並使用jaxb編組。我們應該怎麼做?

+0

哪條線被拋出的異常?向我們展示完整的堆棧跟蹤,而不僅僅是一點。 – skaffman 2011-12-27 11:58:37

+0

錯誤來自'element.soapBody.appendChild(element)'這一行;''元素'屬於'JAXBElement'類型。下面是堆棧跟蹤:'java.lang.ClassCastException:javax.xml.bind.JAXBElement不能轉換爲org.w3c.dom.Element \t at com.staples.onas.util.ONASUtil.createPublishLog(ONASUtil.java: 158) \t at com.staples.onas.service.endpoint.OrderNumberServiceEndPoint.processOrderNumberRequest(OrderNumberServiceEndPoint.java:73) \t at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)''。由於大小限制,我無法在此處粘貼完整的堆棧跟蹤。讓我知道是否需要更多細節。 – 2011-12-30 05:54:55

回答

4

基本上,你必須在你的肩膀上劃傷你的屁股。

使用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變得困難)。

+0

大聲笑@表達開始這個答案:) – 2018-01-24 10:54:29

6

我認爲,我想出了一個稍微更優雅的解決方案:

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