在Go中,您可以将结构编组为
XML,例如:
package main import ( "encoding/xml" "fmt" ) type person struct { Name string Starsign string } func main() { p := &person{"John Smith","Capricorn"} b,_ := xml.MarshalIndent(p,""," ") fmt.Println(string(b)) }
产生输出:
<person> <Name>John Smith</Name> <Starsign>Capricorn</Starsign> </person>
我的问题是,人类型是小写的“p”,因为我希望它是私有的包.但我更喜欢XML元素是大写的:< Person>.结构中的字段可以使用标记(例如`xml:“name”`)对结构字段编组为其他名称,但这似乎不是结构类型的选项.
我有一个使用模板的解决方法,但知道一个更好的答案会很高兴.
解决方法
根据
encoding/xml.Marshal文档:
The name for the XML elements is taken from,in order of preference:
- the tag on the XMLName field,if the data is a struct
- the value of the XMLName field of type xml.Name
- the tag of the struct field used to obtain the data
- the name of the struct field used to obtain the data
- the name of the marshalled type
您可以在结构中的XMLName字段上使用标记来覆盖person结构的XML标记名称.为了避免将它放在您的实际人员结构中,您可以创建一个嵌入您正在编组的人员结构的匿名结构.
package main import ( "encoding/xml" "fmt" ) type person struct { Name string Starsign string } func marshalPerson(p person) ([]byte,error) { tmp := struct { person XMLName struct{} `xml:"Person"` }{person: p} return xml.MarshalIndent(tmp," ") } func main() { p := person{"John Smith",_ := marshalPerson(p) fmt.Println(string(b)) }