'Dynamically adding namespace to SOAP Envelope in Java

I am new to all of this but I am trying to create a SOAP message and get stuck at the off, I am using Java 8 and the standard javax.xml.soap classes but seem unable to add namespaces to the Envelope

MessageFactory factory  = MessageFactory.newInstance();
SOAPMessage message     = factory.createMessage();
SOAPPart part       = message.getSOAPPart();
SOAPEnvelope envelope   = part.getEnvelope();

envelope.addNamespaceDeclaration( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

If I try this at runtime I get the following error NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.



Solution 1:[1]

I have done this now by creating the required envelope definition as an XML String and then setting the SOAPPart content using that string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 david-zed