在Groovy / Grails中使用XmlSlurper来解析Pingdom XML响应

时间:2010-02-16 14:13:11

标签: grails groovy xmlslurper

之前我已成功使用过XmlSlurper,但我正在努力解析以下XML - 它是对Pingdom API调用的响应。我试过遵循名称空间声明示例,但我只是在ns1和ns2值上收到错误消息。任何人都可以帮我指出正确的方向吗? xml看起来像这样: -

<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope 
         xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
         xmlns:ns1="urn:methods" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:ns2="urn:PingdomAPI"
         xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
         SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <SOAP-ENV:Body>
            <ns1:Auth_loginResponse>
                <return xsi:type="ns2:Auth_LoginResponse">
                    <status xsi:type="xsd:int">0</status>
                    <sessionId xsi:type="xsd:string">mysessionId</sessionId>
                </return>
            </ns1:Auth_loginResponse>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

使用XmlSlurper后,它只将0和mysessionId连接成一个字符串

0mysessionId

1 个答案:

答案 0 :(得分:4)

试试这个,让你的xml存储在xml变量中:

def records = new XmlSlurper().parseText(xml).declareNamespace(
    'SOAP-ENV':'http://schemas.xmlsoap.org/soap/envelope/', 
    ns1:'urn:methods', 
    xsd:'http://www.w3.org/2001/XMLSchema', 
    xsi:'http://www.w3.org/2001/XMLSchema-instance',
    ns2:'urn:PingdomAPI'
)

println records.'SOAP-ENV:Body'.'ns1:Auth_loginResponse'.return.status
println records.'SOAP-ENV:Body'.'ns1:Auth_loginResponse'.return.sessionId