Java Reference
In-Depth Information
Adding Namespace Declarations
Problem
You want to add a namespace declaration to your SOAP message.
Solution
Use the SOAPEnvelope.addNamespaceDeclaration method to add a namespace to the en-
velope, then create a QName and use the SOAPBody.addBodyElement method using the
namespace.
Discussion
The following code will create a namespace and associate it with the SOAP envelope and then
create an empty body element that uses that namespace:
//Declare the namespace
SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
env.addNamespaceDeclaration("e", "http://example.com/myNs");
//Use the new namespace in the body
SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
QName bodyName = env.createQName("Quote", "e");
SOAPBodyElement q = body.addBodyElement(bodyName);
To use the namespace within the SOAP body, you create a qualified name and add it to the
body as an element. Here you see the resulting SOAP message that uses this namespace in the
body:
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:e="http://example.com/myNs">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<e:Quote/>...
Note that you must declare the namespace before trying to use it, or you'll get a
javax.xml.soap.SOAPException indicating that it can't find the namespace.
Search WWH ::




Custom Search