如何使用Java SAAJ在Soap Request XML中添加子元素

时间:2017-08-29 18:52:21

标签: java soap groovy soapui saaj

我想在Soap Request的主体中添加子元素(Identifier),如下所示:

预期的肥皂要求

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:ns="nsurl">
<soapenv:Header/>
<soapenv:Body>
  <ns:GetRequest>
     <ns:Identifier Type="x" Value="y"/>      
  </ns:GetRequest>
</soapenv:Body>
</soapenv:Envelope>

使用我的代码,我可以添加子元素(Identifier),如下所示:

实际肥皂要求

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:ns="nsurl">
 <soapenv:Header/>
 <soapenv:Body>
  <ns:GetRequest>
     <ns:Identifier>Type="x" Value="y"</ns:Identifier>      
  </ns:GetRequest>
 </soapenv:Body>
 </soapenv:Envelope>

这是java代码:

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String myNamespace = "ns";
    String myNamespaceURI = "nsurl";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);


    // SOAP Body
    SOAPBody soapBody = envelope.getBody();

    SOAPElement soapBodyElem = soapBody.addChildElement("GetRequest", myNamespace);

    SOAPElement soapBodyElem1 =soapBodyElem.addChildElement("Identifier", myNamespace);
    soapBodyElem1.addTextNode("Type=\"x\" Value=\"y\"");


}

2 个答案:

答案 0 :(得分:1)

您似乎正在使用SoapUI工具。

您可以使用以下脚本中的Groovy Script测试步骤来更改相同内容。

def xmlString = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="nsurl">  <soapenv:Header/>  <soapenv:Body>   <ns:GetRequest>      <ns:Identifier>Type="x" Value="y"</ns:Identifier>         </ns:GetRequest>  </soapenv:Body>  </soapenv:Envelope>"""
def xml = new XmlSlurper().parseText(xmlString)
//Get the Identifier node
def identifier = xml.'**'.find{it.name() == 'Identifier'}

//Create a map based on Identifier node value
def map = identifier.text().split(' ').collectEntries{ [(it.split('=')[0]) : it.split('=')[1].replace('"','')]}

//Remove the text value for Identifier node
identifier.replaceBody { '' }

//Set the attributes from the map
map.each{k,v -> identifier.@"$k" = v}
def newXml = groovy.xml.XmlUtil.serialize(xml)
log.info newXml

您可以在线快速尝试 demo

答案 1 :(得分:0)

在预期请求中,TypeValue是属性,而不是ns:Identifier元素内容的一部分。因此,您需要使用SAAJ的addAttribute(或DOM的setAttributeNS)方法来添加它们。