使用groovy获取XML节点值

时间:2015-07-16 12:03:49

标签: 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>   
        </tem:objUserDetails></tem:getMotorPremium>
     </soapenv:Body>
</soapenv:Envelope>  

我正在尝试从此处获取产品代码

as response [“ns:ProductCode”]但这不会返回。

请咨询

1 个答案:

答案 0 :(得分:1)

给出xml:

def xml = '''<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>   
            |            </tem:objUserDetails>
            |        </tem:getMotorPremium>
            |    </soapenv:Body>
            |</soapenv:Envelope>'''.stripMargin()

你只需要:

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