Reputation: 142
How to marshal without root element?
type Ids struct {
Id []string `xml:"id"`
}
IdsStr, _ := xml.Marshal(&Ids{[]string{"test1", "test2"}})
Output IdsStr is:
<Ids><id>test1</id><id>test2</id></Ids>
It should be without Ids element:
<id>test1</id><id>test2</id>
Upvotes: 1
Views: 1946
Reputation: 4515
...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?
You can use XMLName xml.Name
, tag xml:",chardata"
(etc.) to customize a 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))
}
0utput
<1>XXX</1><2>YYY</2>
👉🏻 also, look at on src/encoding/xml/ to find examples.
Upvotes: 1
Reputation: 4515
type id string
func main() {
IdsStr, _ := xml.Marshal([]id{"test1", "test2"})
fmt.Println(string(IdsStr))
}
or
type id string
type Ids struct {
Vals []id
}
func main() {
ids := &Ids{[]id{"test1", "test2"}}
IdsStr, _ := xml.Marshal(ids.Vals)
fmt.Println(string(IdsStr))
}
0utput
<id>test1</id><id>test2</id>
Upvotes: 2