Groovys XmlSlurper 中的命名空间处理 [英] Namespace handling in Groovys XmlSlurper

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

问题描述

情况:

def str = """
  <foo xmlns:weird="http://localhost/">
    <bar>sudo </bar>
    <weird:bar>make me a sandwich!</weird:bar>
  </foo>
"""
def xml = new XmlSlurper().parseText(str)
println xml.bar

这个片段的输出是

# sudo make me a sandwich!

似乎解析器合并了 的内容.

It seems like the parser merges the contents of <bar> and <weird:bar>.

是否需要这种行为,如果需要,我该如何避免这种情况并仅选择 ?

Is this behavior desired and if yes, how can I avoid this and select only <bar> or <weird:bar>?

推荐答案

默认情况下,XMLSlurper 不支持命名空间.这可以通过使用 declareNamespace 方法.

By default XMLSlurper is not namespace aware. This can be turned on by declaring namespaces with the declareNamespace Method.

def str = """ 
<foo xmlns:weird="http://localhost/">
  <bar>sudo </bar>
  <weird:bar>make me a sandwich!</weird:bar>
</foo>
""" 
def xml = new XmlSlurper().parseText(str).declareNamespace('weird':'http://localhost/')
println xml.bar // without namespace awareness, will print "sudo make me a sandwich!"
println xml.':bar' // will only print "sudo"
println xml.'weird:bar' // will only print "make me a sandwich!"

输出为:

sudo make me a sandwich!
sudo
make me a sandwich!

第一个 println 仍然不能识别命名空间.第二个 println 只会打印没有命名空间的标签.如果您使用第三个 println 中显示的前缀限定元素,您只会获得命名空间标记.

The first println will still not be namespace aware. The second println will only print the tag without namespace. If you qualify element with the prefix shown in the third println you only get the namespaced tag.

这篇关于Groovys XmlSlurper 中的命名空间处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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