如何使用 groovy 获取 XML 属性的值

How to get the value of XML attribute using groovy

我正在尝试在 CanOfferProductResponse 标签内获取属性 xmlns 的值 Groovy

下面是我的 XML-

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body><CanOfferProductResponse xmlns="urn:iQQ:API:22:iQQMessages.xsd"/></SOAP-ENV:Body></SOAP-ENV:Envelope>

我尝试了下面的代码,但它不起作用

def Envelope = new XmlSlurper().parseText(xml) 
println Envelope.Body.CanOfferProductResponse.@xmlns

// 预期输出 = urn:iQQ:API:22:iQQMessages.xsd(在标签内)

我是XML的新手,请帮助我。

XML 命名空间的使用可能会使事情复杂化。如果您知道 XML 代码片段使用了所示的确切名称空间前缀,则可以在 XmlSlurper 中禁用名称空间感知并使用 "prefix:elementName" 作为引用元素。

def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body>
        <CanOfferProductResponse xmlns="urn:iQQ:API:22:iQQMessages.xsd"/>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''

// the second constructor argument controls namespace awareness
def env = new XmlSlurper(false, false).parseText(xml)
def namespace = env.'SOAP-ENV:Body'.CanOfferProductResponse.@xmlns
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'

但是如果默认命名空间并不总是在 CanOfferProductResponse 元素上定义,或者如果命名空间前缀并不总是一致的,例如Envelope 元素具有 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 属性而不是 xmlns:SOAP-ENV=...,那么此方法将不起作用。

命名空间感知方法将涉及调​​用 lookupNamespace 方法并传入一个空字符串参数(这意味着该元素的默认命名空间):

// by default, XmlSlurper instances are namespace aware
def env = new XmlSlurper().parseText(xml)
def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'

但是由于命名空间是继承的,这种方法意味着 lookupNamespace 方法仍然 return 'urn:iQQ:API:22:iQQMessages.xsd' 即使实际上没有 xmlns 属性CanOfferProductResponse 元素,例如

def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns="urn:iQQ:API:22:iQQMessages.xsd">
    <SOAP-ENV:Body>
        <CanOfferProductResponse />
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''

def env = new XmlSlurper().parseText(xml)
def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'

(此示例使用 Groovy 2.5 执行)