【问题标题】:XML unmarshal does not respect the root element namespace prefix definitionXML unmarshal 不遵守根元素命名空间前缀定义
【发布时间】:2015-09-21 22:32:53
【问题描述】:

这里是 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 命名空间而不是前缀。这是code

有什么方法可以使 marshal/unmarshal 不会改变 xml 结构?谢谢!

【问题讨论】:

标签: go xml-parsing


【解决方案1】:

看起来并没有改变逻辑结构。在您的原始输入中,root 元素为命名空间 http://test.com/testns 声明了前缀 test,但它实际上并未声明自己位于该命名空间中。

这是一个替代版本,可以满足您的需求:https://play.golang.org/p/NqNyIyMB4IP

我将命名空间提升到 Root 结构,并将 test: 前缀添加到输入中的 root xml 元素。

【讨论】:

  • 虽然我不确定它是否正确处理了title 元素。当命名空间用xmlns:test 声明并且title 元素名称没有前缀时,我不相信它应该在命名空间中。但是,在处理后的版本中,使用原始的 xmlns 声明,所有子级都自动位于命名空间中......正如@RoninDev 提到的,stdlib xml 库在命名空间方面并不是那么好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
相关资源
最近更新 更多