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

问题描述 投票:0回答:1

我想获取属性的值。xmlns 里面 CanOfferProductResponse 标签在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 (在Tag里)

我是一个新的XML,请帮助我,我试图在Groovy中的CanOfferProductResponse标签中获取属性xmlns的值。

xml groovy xml-parsing xmlslurper
1个回答
2
投票

XML命名空间的使用也许使事情变得复杂。如果你知道XML片段使用的是如图所示的确切的命名空间前缀,你可以在XmlSlurper中禁用命名空间意识,并使用 "前缀:元素名称 "作为引用元素。

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 方法传递一个空的String参数(这意味着该元素的默认命名空间)。

// 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 方法仍然会返回'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执行的)

© www.soinside.com 2019 - 2024. All rights reserved.