gpt4 book ai didi

Groovy XML 和 "xml:"命名空间

转载 作者:行者123 更新时间:2023-12-04 11:12:52 24 4
gpt4 key购买 nike

我正在编写几个脚本来修改 xml 文件。有问题的文件使用 xml:lang 元素。 Groovy (XmlSlurper) 似乎正在插入一个 tag0 命名空间,我不会太介意,除了它似乎破坏了 XmlUtil 的后续处理。

一个例子:

import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil

String source = """<?xml version='1.0' encoding='UTF-8'?>
<root>
<one xml:lang="en">First</one>
<one xml:lang="de">Second</one>
</root>
"""

def root = new XmlSlurper().parseText(source).declareNamespace(xml: "http://www.w3.org/XML/1998/namespace")
println root
String xml = new StreamingMarkupBuilder().bind{
mkp.xmlDeclaration()
out << root
}
println xml
println XmlUtil.serialize(xml)

结果是
[Fatal Error] :2:44: The value of the attribute "prefix="xmlns",localpart="tag0",rawname="xmlns:tag0"" is invalid. Prefixed namespace bindings may not be empty.

默认情况下 xml: 命名空间应该存在,我已经尝试使用 .declareNamespace() 添加它,但它似乎没有帮助。我觉得我遗漏了一些明显的东西,但谷歌无法告诉我它是什么。

最佳答案

找到 this thread从几年前开始,它说:

The problem is that the original document uses the default namespace.

SMB does not normally use the default namespace so it invents a tag and uses it to explicitly mark each element in the namespace. As far as an XML parser is concerned it doesn't matter how the namespace is indicated. However there are cosmetic reasons why it is sometimes desirable to use default namespaces.

If you put mkp.declareNamespace("": "http://java.sun.com/xml/ns/j2ee") as the first line in your builder closure you should get the output you want.


但是,这似乎不起作用
我发现的唯一解决方案是让 Slurper 忽略命名空间和验证;
def root = new XmlSlurper(false,false).parseText(source)

关于Groovy XML 和 "xml:"命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9582566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com