使用groovy XMLParser读取名称空间/SOAP响应中的xml值
我正在使用groovy文件,其中使用xmlParser生成XML.现在,我想获取xml的标记值.
I'm using a groovy file where I used xmlParser to generate XML.Now, I want to get the tag values of the xml.
这是我的代码
def rootnode = new XmlParser().parseText(responseXml);
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()
I have tried like rootnode.Status[0].text()
但是没有得到. 如何获得其中的状态"值?有点困惑.
However its not getting. How can I get "Status" value in it? Little confused.
谢谢
只需使用路径"到您感兴趣的var.您必须引用"命名空间(这意味着,使用字符串作为访问器,因为:
和-
之类的字符将被groovy解释)或使用groovy.xml.Namespace
帮助器.例如. (请参阅评论):
Just use the "path" down to the var you are interested. You either have to "quote" the namespaces (that means, use strings as accessors, as chars like :
and -
would be interpreted by groovy) or use the groovy.xml.Namespace
helper. E.g. (see comments):
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'