使用groovy脚本比较xml响应的内容

时间:2016-06-07 22:50:45

标签: xml web-services soap groovy

我有2个xml的回复,并且只想比较主要内容

示例如下:

XML1:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <soapenv:Header>
          <ebl:RequesterCredentials soapenv:mustUnderstand="0" xmlns:ns="urn:apis:eBLBaseComponents" xmlns:ebl="urn:apis:eBLBaseComponents">         
          </ebl:RequesterCredentials>
       </soapenv:Header>
       <soapenv:Body>
          <UserResponse xmlns="urn:apis:eBLBaseComponents">
          <Name>Sam</Name>
          <ID>98765</ID>
          <City>SFO</City>
          </UserResponse>
       </soapenv:Body>
    </soapenv:Envelope>

XML2:

<soap:Envelope xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:apis:eBLBaseComponents" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

       <soap:Body>
        <UserResponse>
          <Name>Sam</Name>
          <ID>98764</ID>
          <City>SFO</City>
          </UserResponse>
     </soap:Body>
    </soap:Envelope>

我想只比较UserResponse中的内容,并且喜欢忽略所有其他内容。我刚刚给出了上面的示例,其中我只提到了响应中的3个元素。我有一些用例,我将看到100个元素作为响应,并希望比较所有这100个元素的响应。请建议如何继续使用Groovy脚本。

1 个答案:

答案 0 :(得分:0)

这适用于Groovy 2.4.5:

def xml1 = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <soapenv:Header>
          <ebl:RequesterCredentials soapenv:mustUnderstand="0" xmlns:ns="urn:apis:eBLBaseComponents" xmlns:ebl="urn:apis:eBLBaseComponents">         
          </ebl:RequesterCredentials>
       </soapenv:Header>
       <soapenv:Body>
          <UserResponse xmlns="urn:apis:eBLBaseComponents">
          <Name>Sam</Name>
          <ID>98765</ID>
          <City>SFO</City>
          </UserResponse>
       </soapenv:Body>
    </soapenv:Envelope>
"""

def xml2 = """
<soap:Envelope xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:apis:eBLBaseComponents" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

       <soap:Body>
        <UserResponse>
          <Name>Sam</Name>
          <ID>98764</ID>
          <City>SFO</City>
          </UserResponse>
     </soap:Body>
    </soap:Envelope>
"""

def xs1 = new XmlSlurper().parseText(xml1)
def xs2 = new XmlSlurper().parseText(xml2)

def nameCheck = (xs1.Body.UserResponse.Name.text() == xs2.Body.UserResponse.Name.text())
def idCheck = (xs1.Body.UserResponse.ID.text() == xs2.Body.UserResponse.ID.text())
def cityCheck = (xs1.Body.UserResponse.City.text() == xs2.Body.UserResponse.City.text())

println "nameCheck: ${nameCheck} idCheck: ${idCheck} cityCheck: ${cityCheck}"