简体   繁体   中英

How to append JAXBElement as a child of SOAPBody for a SOAP Message

How to append JAXBElement as a child of SOAPBody for a SOAP Message. What i am trying to do inside my web service endpoint method is:

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

Then i get the java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to org.w3c.dom.Element .

I am working spring-WS and using jaxb marshaller. How can we do this?

I think that I came up with a slightly more elegant solution:

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

Basically, you have to go over your shoulder to scratch your ass.

Use the JAXBContext to create a marshaller, converting it all to a string. Then convert the string to an xml element.

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;

There is one more option. Use XmlBeans to build your classes (which will make using JAXB difficult and therefore JAX-WS).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM