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

标签 xml go marshalling

如何在没有根元素的情况下进行编码(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/

相关文章:

android - 为什么 AndroidStudio 显示警告 "Namespace declaration is never used"?

arrays - 如何在 crypto.rand.Read 中使用 [20]bytes 类型作为参数而不是 []bytes?

java - JAX-RS 多态 POST 请求 : how should I write my JSON?

C# Marshal.Copy Intptr 到 16 位托管无符号整数数组

Android:在 XML 中使用 StreetViewPanoramaView

Android,XML解析类似于E4X?

c# - 如何按属性值对 linq 中的 XML 文档进行排序?

go - 如何测试光纤参数

go - 从 DynamoDB 获取最新的多个值

json - 从编码结构 Golang 中删除转义字符