簡體   English   中英

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

[英]How to add child elements in Soap Request XML using Java SAAJ

我想在Soap Request的正文中添加子元素(標識符),如下所示:

預期的肥皂要求

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


}

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

您可以快速在線試用

在預期的請求中, TypeValue是屬性,而不是ns:Identifier元素內容的一部分。 因此,您需要使用SAAJ的addAttribute (或DOM的setAttributeNS )方法添加它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM