How to add prefix to the child elements of SOAP client?

4.9k Views Asked by At

I need to write a SOAP client to send a request message, I could successfully send the request but I need to amend the message, the only required modification is to add prefix to the child elements. Once I've used the following code but nothing happen.

WebsiteConfigID.addNamespaceDeclaration("v3", "http://tnwebservices.ticketnetwork.com/tnwebservice/v3.2");

Current output

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" 
              xmlns:v3="http://tnwebservices.ticketnetwork.com/tnwebservice/v3.2">
   <env:Header/>
   <env:Body>
       <GetEvents>
          <websiteConfigID>1111</websiteConfigID>
          <cityZip>Paris</cityZip>
       </GetEvents>
   </env:Body>
</env:Envelope>

Expected output

 <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" 
              xmlns:v3="http://tnwebservices.ticketnetwork.com/tnwebservice/v3.2">
   <env:Header/>
   <env:Body>
       <v3:GetEvents>     <<prefix is added
          <v3:websiteConfigID>1111</v3:websiteConfigID>  <<prefix is added
          <v3:cityZip>Paris</v3:cityZip>  <<prefix is added
       </v3:GetEvents>  
   </env:Body>
 </env:Envelope>

Code

    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();

    SOAPConnection connection = soapConnectionFactory.createConnection();

    SOAPMessage message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();



    SOAPBody body = message.getSOAPBody();
    SOAPPart part = message.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    envelope.addNamespaceDeclaration("v3", "http://tnwebservices.ticketnetwork.com/tnwebservice/v3.2");
    SOAPFactory soapFactory = SOAPFactory.newInstance();

    Name bodyName;
    bodyName = soapFactory.createName("GetEvents");

    SOAPBodyElement getEvents = body.addBodyElement(bodyName);
    Name childName = soapFactory.createName("websiteConfigID");
    SOAPElement WebsiteConfigID = getEvents.addChildElement(childName);
    WebsiteConfigID.addTextNode("1111");

    childName = soapFactory.createName("cityZip");
    SOAPElement CityZip = getEvents.addChildElement(childName);
    CityZip.addTextNode("Paris");

    message.writeTo(System.out);
1

There are 1 best solutions below

1
On BEST ANSWER

Use the SOAPFactory methods which take QName, or prefix and uri information. For example, instead of calling bodyName = soapFactory.createName("GetEvents");, it should be

bodyName = soapFactory.createName("GetEvents", "v3",
   "http://tnwebservices.ticketnetwork.com/tnwebservice/v3.2");

Refer to here for more details on createName method