问题描述
当我使用此代码输出一些我用 XmlParser
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 进行一些调整,以通过 XML 执行 2 次传递,首先收集所有使用的命名空间,然后将它们输出到顶部而不是每个内部命名空间节点.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 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!