微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

xml-serialization – 转到XML编组和根元素

在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))
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。