随时间变化的名称空间进行Groovy XML解析 [英] Groovy XML Parsing with namespaces which are changing everytime
问题描述
我正在尝试解析具有名称空间的BPEL Management API响应.我不想看到所有内容,然后对其进行标记.
I'm trying to parse BPEL Management API response which has its namespaces. I do not want to see them all and then mark it.
因此,在开始解析它之前,我想即时收集XML中所有已声明的名称空间.
Hence before to start parse it, I want to collect all the declared namespaces in the XML on the fly.
如何通过Groovy获取文档中所有已声明的XML名称空间?
How to get all the declared XML namespaces in the document via Groovy ?
推荐答案
获取使用的名称空间列表的一种方法是访问每个元素并获取namespaceURI:
One way to get the list of namespaces used is to visit each element and get the namespaceURI:
def s = """
<?xml version="1.0" encoding="utf-8"?>
<b:root xmlns:a="http://a.example.com" xmlns:b="http://b.example.com" xmlns:c="http://c.example.com" xmlns:d="http://d.example.com">
<a:name>Test A</a:name>
<b:name>Test B</b:name>
<b:stuff>
<c:foo>bar</c:foo>
<c:baz>
<d:foo2/>
</c:baz>
</b:stuff>
<nons>test</nons>
<c:test/>
</b:root>
""".trim()
def xml = new XmlSlurper().parseText(s)
def namespaceList = xml.'**'.collect { it.namespaceURI() }.unique()
assert ['http://b.example.com',
'http://a.example.com',
'http://c.example.com',
'http://d.example.com',
""] == namespaceList
另一种方法是使用反射来访问 GPathResult 类的受保护的 namespaceTagHints 属性,该属性是 groovy.util.slurpersupport.NodeChild .
Another way is to use reflection to access the protected namespaceTagHints property of the GPathResult class, which is the superclass of groovy.util.slurpersupport.NodeChild.
def xml = new XmlSlurper().parseText("<...>")
def xmlClass = xml.getClass()
def gpathClass = xmlClass.getSuperclass()
def namespaceTagHints = gpathClass.getDeclaredField("namespaceTagHints")
namespaceTagHints.setAccessible(true)
println namespaceTagHints.get(xml)
// returns ==> [b:http://b.example.com, a:http://a.example.com, d:http://d.example.com, c:http://c.example.com]
仅需注意,默认情况下,XmlSlurper不需要名称空间声明即可浏览文档,因此,只要元素/属性名称是唯一的,通常就不必担心名称空间.
Just a note, by default XmlSlurper does not require namespace declarations to navigate the document, so as long as the element/attribute names are unique you typically do not have to worry about namespaces at all.
这篇关于随时间变化的名称空间进行Groovy XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!