如何打印一个名称空间保持不变的Groovy节点? [英] How do I print a groovy Node with namespace preserved?

查看:121
本文介绍了如何打印一个名称空间保持不变的Groovy节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用这段代码输出一些XML时,我用 XmlParser
$ b

When I use this code to output some XML I parsed (and modified) with XmlParser

XmlParser parser = new XmlParser()
def root = parser.parseText(feedUrl.toURL().text)
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
println writer.toString()

根节点上的名称空间声明不会被打印,即使它们存在于 root toString()中......任何想法?

the namespace declarations on the root node are not printed, even though they are there in the toString() of root... any ideas?

推荐答案

它看起来像是对输出进行非规范化处理,并且包含名称空间上下文以及实际需要名称空间上下文的节点。

It looks like it's denormalizing the output and including the namespace context along with the nodes that actually need the namespace context.

例如,此问题的网页附带了creativeCommons命名空间嵌入:

For example, the webpage for this question comes in with creativeCommons namespace embedded:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
  <!-- snip -->
  <creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
  <!-- snip -->
</feed>

当您使用此脚本输出xml时:

When you output the xml using this script:

def root = new XmlParser().parseText("http://stackoverflow.com/feeds/question/227447".toURL().text)
println new XmlNodePrinter().print(root)

它将命名空间移动到需要该许可证的节点命名空间。在这种情况下不是一个大问题,因为该名称空间中只有一个节点。如果大部分XML都是命名空间,那么它可能会让事情变得更加糟糕。

It ends up moving the namespace to the license node that needs that namespace. Not a huge deal in this case as there is only a single node in that namespace. If most of the XML were namespaced, it'd probably bloat things quite a bit more.

<feed xmlns="http://www.w3.org/2005/Atom">
  <!-- snip -->
    <creativeCommons:license xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">
http://www.creativecommons.org/licenses/by-nc/2.5/rdf
  </creativeCommons:license>
  <!-- snip -->
</feed>

如果您确实希望节点规格化,则必须对XmlNodePrinter进行一些调整才能执行2通过XML,首先收集所有使用的命名空间,第二步将它们输出到顶部,而不是在每个命名空间节点内输出。 Groovy源代码实际上非常易读,如果你真的需要这样的话,不会很难修改。

If you actually wanted the nodes normalized, you'd have to make some tweaks to the XmlNodePrinter to do 2 passes through the XML, first to gather all of the used namespaces and 2nd to output them at the top rather than within each namespaced node. The groovy source code is actually pretty readable and wouldn't be that hard to modify if you actually needed this.

这篇关于如何打印一个名称空间保持不变的Groovy节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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