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

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

问题描述

现状:

The situation:

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

这段代码的输出是

The output of this snippet is

# sudo make me a sandwich!

好像解析器合并< bar> code>和< weird:bar>

是否需要此行为?我可以避免这种情况,只选择< bar> < weird:bar>

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

推荐答案

默认情况下,XMLSlurper不支持名称空间。这可以通过使用 declareNamespace Method
$ b

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!"

输出结果为:

The output is:

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天全站免登陆