【问题标题】:How to add child elements in Soap Request XML using Java SAAJ如何使用 Java SAAJ 在 Soap 请求 XML 中添加子元素
【发布时间】:2017-08-29 18:52:20
【问题描述】:

我想在 Soap 请求的正文中添加子元素(标识符),如下所示:

预期的肥皂请求

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

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

实际肥皂请求

 <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\"");


}

【问题讨论】:

    标签: java soap groovy soapui saaj


    【解决方案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

    【讨论】:

    • 这个答案可能离题了。我猜 OP 将问题标记为“soapui”只是因为预期的请求是使用 SoapUI 生成的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多