GoLang XML 编组定制(无根元素的编组)

GoLang XML marshalling customization (marshal without root element)

没有根元素如何编组?

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

type id string 

func main() {
    IdsStr, _ := xml.Marshal([]id{"test1", "test2"})
    fmt.Println(string(IdsStr))
}

Playground

type id string

type Ids struct {
    Vals []id 
}

func main() {
    ids := &Ids{[]id{"test1", "test2"}}
    IdsStr, _ := xml.Marshal(ids.Vals)
    fmt.Println(string(IdsStr))
}

Playground

0输出

<id>test1</id><id>test2</id>

...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/ 以查找示例。