gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:18:55 27 4
gpt4 key购买 nike

我想在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com