当我解组该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
最佳答案
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"`
}
关于xml - 在Go中编码(marshal)XML时如何保留标签的 namespace url,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41776930/