使用groovy XMLParser读取名称空间/ SOAP响应中的xml值

时间:2015-01-23 09:24:38

标签: groovy

我正在使用一个groovy文件,我使用xmlParser生成XML。现在,我想获取xml的标记值。

这是我的代码

def rootnode = new XmlParser()。parseText(responseXml);

输出

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:creditCard">
    <SOAP-ENV:Body><ns1:creditCardResponse xmlns:ns1="urn:creditCard">
        <return xsi:type="tns:RPResponse">
            <Status xsi:type="xsd:int">0</Status>

        </return>
    </ns1:creditCardResponse>
</SOAP-ENV:Body>

我尝试过rootnode.Status [0] .text()

然而它没有得到。 我怎样才能获得“状态”值?有点困惑。

谢谢,

1 个答案:

答案 0 :(得分:0)

只需使用&#34;路径&#34;到你感兴趣的var。你要么必须引用&#34;引用&#34;命名空间(也就是说,使用字符串作为访问器,如:-之类的字符将由groovy解释)或使用groovy.xml.Namespace帮助器。例如。 (见评论):

def xml = new groovy.util.XmlParser().parseText('''\
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:creditCard">
    <SOAP-ENV:Body><ns1:creditCardResponse xmlns:ns1="urn:creditCard">
        <return xsi:type="tns:RPResponse">
            <Status xsi:type="xsd:int">666</Status>

        </return>
    </ns1:creditCardResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
''')

// XXX namespaces quoted
assert xml.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.Status.text()=='666'

// XXX access by namespace
def nsSoapEnv = new groovy.xml.Namespace('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV')
def nsNs1 = new groovy.xml.Namespace('urn:creditCard', 'ns1')
assert xml[nsSoapEnv.Body][nsNs1.creditCardResponse].return.Status.text()=='666'