无法使用groovy获取所有XML标记值

时间:2015-07-17 07:13:21

标签: xml groovy

我正在尝试获取一个属性的xml节点。但它没有正确取得

这是我的回复

def response = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:ns="http://schemas.datacontract.org/2004/07/" xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<soapenv:Header/>
     <soapenv:Body>
     <tem:getMotorPremium><tem:objUserDetails>                
         <ns:ProductCode>2311</ns:ProductCode>   
         <ns:ProductId>2311</ns:ProductId>   
         <ns:ProductName>2311</ns:ProductName>   
        </tem:objUserDetails></tem:getMotorPremium>
     </soapenv:Body>
</soapenv:Envelope>  

我通过以下方式获得每个值。

def code = new XmlSlurper().parseText(response)
                       .Body
                       .getMotorPremium
                       .objUserDetails
                       .ProductCode
                       .text()

def Id = new XmlSlurper().parseText(response)
                       .Body
                       .getMotorPremium
                       .objUserDetails
                       .ProductId
                       .text()

def Name = new XmlSlurper().parseText(response)
                       .Body
                       .getMotorPremium
                       .objUserDetails
                       .ProductName
                       .text()

我不想一直使用“新的XmlSlurper()。parseText(响应).Body.getMotorPremium.objUserDetails”

我使用过这样的东西来试试,但它不起作用..请建议

def ab = new XmlSlurper().parseText(response).Body.getMotorPremium.objUserDetails
    logInfo("Product code :"+ab.ProductCode.text());
    logInfo("Product Id :"+ab.ProductId.text());
    logInfo("Product Name :"+ab.ProductName.text());

1 个答案:

答案 0 :(得分:0)

以下代码完美无缺:

def response = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:ns="http://schemas.datacontract.org/2004/07/" xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<soapenv:Header/>
     <soapenv:Body>
     <tem:getMotorPremium><tem:objUserDetails>                
         <ns:ProductCode>2311</ns:ProductCode>   
         <ns:ProductId>2312</ns:ProductId>   
         <ns:ProductName>2313</ns:ProductName>   
        </tem:objUserDetails></tem:getMotorPremium>
     </soapenv:Body>
</soapenv:Envelope>
"""
def ab = new XmlSlurper().parseText(response).Body.getMotorPremium.objUserDetails
println("Product code :"+ab.ProductCode.text())
println("Product Id :"+ab.ProductId.text())
println("Product Name :"+ab.ProductName.text())
ab.with {
    println("Product code :"+it.ProductCode.text())
    println("Product Id :"+it.ProductId.text())
    println("Product Name :"+it.ProductName.text())
}

也许这是logInfo问题?