【问题标题】:How to keep the namespace url of a tag when Marshaling XML in Go在 Go 中编组 XML 时如何保留标签的命名空间 url
【发布时间】:2017-01-21 07:41:57
【问题描述】:

当我解组和编组此 XML 时,命名空间的 URL 消失:

<root xmlns:urn="http://test.example.com">
    <urn:copyright>tekst</urn:copyright>
</root>

变成:

<root xmlns:urn="">
    <urn:copyright></urn:copyright>
</root>

代码:

package main

import (
    "encoding/xml"
    "fmt"
)

type Root struct {
    XMLName      xml.Name     `xml:"root"`
    XmlNS        string       `xml:"xmlns:urn,attr"`
    Copyright    Copyright    `xml:"urn:copyright,omitempty"`
}

type Copyright struct {
    Text string `xml:",chardata"`
}

func main() {
    root := Root{}

    x := `<root xmlns:urn="http://test.example.com">
               <urn:copyright>text</urn:copyright>
          </root>`
    _ = xml.Unmarshal([]byte(x), &root)
    b, _ := xml.MarshalIndent(root, "", "    ")
    fmt.Println(string(b))
}

https://play.golang.org/p/1jSURtWuZO

【问题讨论】:

标签: xml go marshalling unmarshalling


【解决方案1】:

Root.XmlNS 未解组。

"The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/." https://www.w3.org/TR/REC-xml-names/

根据 XML 规范和 Go 解组规则 xml:"http://www.w3.org/2000/xmlns/ urn,attr" 应该可以工作,但不能。我认为维护者不会喜欢接下来的编组复杂性。

您可能想要执行以下操作。

    type Root struct {
        XMLName      xml.Name     `xml:"root"`
        Copyright    Copyright    `xml:"http://test.example.com copyright"`
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2015-09-20
    • 1970-01-01
    相关资源
    最近更新 更多