如何在SOAP客户端的子元素中添加前缀?

时间:2014-07-31 02:06:38

标签: java soap javax.xml

我需要编写一个SOAP客户端来发送请求消息,我可以成功发送请求但我需要修改消息,唯一需要修改的是为子元素添加前缀。 一旦我使用了以下代码,但没有任何事情发生。

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

当前输出

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

预期输出

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

代码

    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 个答案:

答案 0 :(得分:1)

使用带SOAPFactory的{​​{1}}方法,或前缀和uri信息。例如,不应该调用QName,而应该是

bodyName = soapFactory.createName("GetEvents");

Refer to here for more details on createName method