如何将JAXBElement作为SOAP消息的SOAPBody的子项追加

时间:2011-12-27 11:55:23

标签: java soap jaxb spring-ws

如何将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);

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

我正在使用spring-WS并使用jaxb marshaller。我们怎么做到这一点?

2 个答案:

答案 0 :(得分:7)

我认为我想出了一个更优雅的解决方案:

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

答案 1 :(得分: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)。