如何在Go中封送XML时保留标记的名称空间URL

时间:2017-01-21 07:41:58

标签: xml go marshalling unmarshalling

当我解组并封送此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

1 个答案:

答案 0 :(得分:0)

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"`
    }