英文:
XML unmarshal does not respect the root element namespace prefix definition
问题
以下是XML结构的翻译:
这是XML结构:
<root xmlns:test="http://test.com/testns">
<test:sub>
<title>this is title</title>
</test:sub>
</root>
它使用下面定义的结构进行解组:
type Root struct {
XMLName xml.Name `xml:"root"`
Sub *Sub
}
type Sub struct {
XMLName xml.Name `xml:"http://test.com/testns sub"`
Title string `xml:"title"`
}
这是解组后的结果:
<root>
<sub xmlns="http://test.com/testns">
<title>this is title</title>
</sub>
</root>
在编组后,根命名空间前缀定义被移除,子元素使用URL命名空间而不是前缀。这是代码的链接:1
有没有办法使编组/解组不改变XML结构?谢谢!
英文:
Here is the XML structure:
<root xmlns:test="http://test.com/testns">
<test:sub>
<title>this is title</title>
</test:sub>
</root>
It gets unmarshalled with the structs defined below:
type Root struct {
XMLName xml.Name `xml:"root"`
Sub *Sub
}
type Sub struct {
XMLName xml.Name `xml:"http://test.com/testns sub"`
Title string `xml:"title"`
}
This is what gets marshalled back:
<root>
<sub xmlns="http://test.com/testns">
<title>this is title</title>
</sub>
</root>
The root namespace prefix definition gets removed after the marshal and the sub element is using url namespace instead of the prefix. Here is the code
Is there any way that marshal/unmarshal won't change the xml structure? thanks!
答案1
得分: 1
看起来它没有改变逻辑结构。在你的原始输入中,root
元素声明了一个前缀 test
,用于命名空间 http://test.com/testns
,但它实际上并没有声明自己在该命名空间中。
这里有一个替代版本,它实现了你想要的效果:https://play.golang.org/p/NqNyIyMB4IP
我将命名空间提升到了 Root
结构体,并在输入中的 root
xml 元素上添加了 test:
前缀。
英文:
It doesn't look like it changed the logical structure. In your original input, the root
element declares a prefix test
for the namespace http://test.com/testns
but it doesn't actually declare itself to be in that namespace.
Here's an alternate version that does what it looks like you want: https://play.golang.org/p/NqNyIyMB4IP
I bumped the namespace up to the Root
struct and added the test:
prefix to the root
xml element in the input.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论