Groovy XmlSlurper:获取具有关联命名空间的属性的值 [英] Groovy XmlSlurper: get value of attribute that has an associated namespace

查看:98
本文介绍了Groovy XmlSlurper:获取具有关联命名空间的属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文档,其中包含具有限定名称的属性.我想使用XmlSlurper获取属性值,但是尝试在不指定名称空间的情况下访问属性是行不通的(下面是一个最小的示例).

I have an XML document that contains attributes with qualified names. I want to get the attribute value using XmlSlurper, but trying to access the attribute without specifying the namespace does not work (below is a minimal example).

def rootNode = new XmlSlurper().parseText(
'''<root xmlns:ex="http://example.com">
     <one ex:a1="uno!"/>
     <ex:two>Some text!</ex:two>
   </root>''' )

assert rootNode.one[0].@a1.text() == 'uno!'

rootNode.one[0].@a1.text()将产生一个空字符串.如果使用rootNode.one[0].'@ex:a1'.text(),我们将获得正确的值,但这取决于文档中使用的名称空间前缀-不能依赖于其他文档的名称空间前缀,因此重要的是关联的名称空间.

rootNode.one[0].@a1.text() will yield an empty string. If using rootNode.one[0].'@ex:a1'.text() we get the correct value, but this is dependent on the namespace prefix used in the document - and that can't be relied upon to be the same for other documents, the associated namespace is what matters.

所以问题是: 如何使用XmlSlurper来访问具有关联名称空间的属性的属性值,而无需指定名称空间前缀? (如果需要提供整个名称空间就可以了)

So the question is: How can XmlSlurper be used to access an attribute value of an attribute that has an associated namespace without the need to specify the namespace prefix? (it would be OK if supplying the whole namespace is needed)

推荐答案

我认为,如果不指定此类名称空间,就无法访​​问具有关联名称空间的属性.否则,仅名称的本地部分"将用于包含属性的地图,从而导致类似此旧错误(Groovy 1.7.5).

I think that accessing an attribute with an associated namespace can't be done without specifying such namespace. Otherwise, only the "local part of the name" would be used for the map holding the attributes, leading to situations like this old bug (groovy 1.7.5).

也许最好的方法是使用 groovy.xml.Namespace 并使用它来访问属性:

Maybe the best way to do that is to use groovy.xml.Namespace and use it to access the attribute:

import groovy.xml.Namespace

def xml = '''
<root xmlns:ex="http://example.com">
    <one ex:a1="uno!"/>
    <ex:two>Some text!</ex:two>
</root>'''
def ns = new Namespace('http://example.com', 'ex')

def slurper = new XmlSlurper(false, true)
def slurped = slurper.parseText(xml)
assert 'uno!' == slurped.one[0].attributes()[ns.a1.toString()]

def parser = new XmlParser(false, true)
def parsed = parser.parseText(xml)
assert 'uno!' == parsed.one[0].attributes()[ns.a1]

这篇关于Groovy XmlSlurper:获取具有关联命名空间的属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆