加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:06:40 所属栏目:百科 来源:网络整理
导读:在Go中,您可以将结构编组为 XML,例如: package mainimport ( "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))}
在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))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读