gpt4 book ai didi

xml - GoLang XML编码(marshal)处理自定义(无根元素的编码(marshal))

转载 作者:行者123 更新时间:2023-12-01 20:24:39 67 4
gpt4 key购买 nike

如何在没有根元素的情况下进行编码(marshal)?

type Ids struct {
Id []string `xml:"id"`
}

IdsStr, _ := xml.Marshal(&Ids{[]string{"test1", "test2"}})
输出IdsStr为:
<Ids><id>test1</id><id>test2</id></Ids>
应该没有Ids元素:
<id>test1</id><id>test2</id>
Playground

最佳答案

...But how can I set voluntary xml names for elements? Vals []id xml:"idSomeOther" returns id after xml marshaled because it's name of type... I need to customize type id to type IdXml but xml marshaled should return id. How can I get it?


您可以使用 XMLName xml.Name,标签 xml:",chardata"(等)来自定义 struct
type Customs struct {
Vals []CustomXml
}

type CustomXml struct {
XMLName xml.Name
Chardata string `xml:",chardata"`
}

func main() {
customs := Customs{
[]CustomXml{
{XMLName: xml.Name{Local: "1"}, Chardata: "XXX"},
{XMLName: xml.Name{Local: "2"}, Chardata: "YYY"}},
}
res, _ := xml.Marshal(customs.Vals)
fmt.Println(string(res))
}
0输出
<1>XXX</1><2>YYY</2>
Playground
👉🏻另外,在 src/encoding/xml/上查找示例。

关于xml - GoLang XML编码(marshal)处理自定义(无根元素的编码(marshal)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63893084/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com