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

标签 java soap groovy soapui saaj

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

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

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

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


}

最佳答案

看来您正在使用 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

关于java - 如何使用 Java SAAJ 在 Soap Request XML 中添加子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946391/

相关文章:

java - 通过 ProcessBuilder 将字符串传递给批处理文件

java - Jersey 远程 IP 地址无法正常工作

java - 在 JAX-WS 代码优先方法中根据模式验证 soap 请求

java - 在 Tomcat Grails 中禁用缓存

java - Eclipse Java 在注释中发现 "cannot be resolved"错误?

java - 文本文件转换为数组列表时出现问题

soap - 在 switchyard 中从 WSDL 创建 Java 文件时出现 java.lang.reflect.InitationTargetException

python - 如何使用 SOAPpy 创建非标准类型?

groovy - 在geb模块中查找直接子模块

android - 在 android studio 的 build.gradle 中使用 flavor 维度