Emil Iakoupov
Emil Iakoupov

Reputation: 189

How to insert XML into soap header in Java

Is there a clean way (no string concatenation) to insert an XML document into a soap header? I used JAXB to compile schemas and now i need to wrap it in soap envelope. for the body i used:

SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
soapMessage.getSOAPBody().addDocument(userDataDocument);

now for the header i also need to add a document, but the API does not have an

addDocument

Previously i used string concatenation, which is easy but not the most flexible way in my mind. I am not just adding a single Qname but a whole XML doc. Is there any way to accomplish this?

Upvotes: 3

Views: 2449

Answers (1)

Emil Iakoupov
Emil Iakoupov

Reputation: 189

figured this out using the source for addDocument...

public static SOAPBodyElement addDocumentToSoapHeader(Document document, SOAPMessage soapMessage) throws SOAPException {
    SOAPBodyElement newBodyElement = null;
    DocumentFragment docFrag = document.createDocumentFragment();
    Element rootElement = document.getDocumentElement();
    if(rootElement != null) {
        docFrag.appendChild(rootElement);
        Document ownerDoc = soapMessage.getSOAPHeader().getOwnerDocument();
        org.w3c.dom.Node replacingNode = ownerDoc.importNode(docFrag, true);
        //this.addNode(replacingNode);
        soapMessage.getSOAPHeader().appendChild(replacingNode);

    }

    return newBodyElement;
}

Upvotes: 3

Related Questions