结构体类型数据转xml字符串
type Plant struct {
XMLName xml.Name `xml:"plant"`
ID int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
coffee := &Plant{
ID: 27,
Name: "Coffee",
}
coffee.Origin = []string{"Ethiopia", "Brazil"}
out, _ := xml.MarshalIndent(coffee, "->", " ")
fmt.Println(string(out))
-><plant id=“27”>
-> <name>Coffee</name>
-> <origin>Ethiopia</origin>
-> <origin>Brazil</origin>
-></plant>
也可以添加头部描述
out, _ := xml.MarshalIndent(coffee, "", " ")
fmt.Println(xml.Header + string(out))
<?xml version=“1.0” encoding=“UTF-8”?>
<plant id=“27”>
<name>Coffee</name>
<origin>Ethiopia</origin>
<origin>Brazil</origin>
</plant>
结构体类型嵌套数据转xml字符串
type Plant struct {
XMLName xml.Name `xml:"plant"`
ID int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
coffee := &Plant{
ID: 27,
Name: "Coffee",
}
coffee.Origin = []string{"Ethiopia", "Brazil"}
tomato := &Plant{
ID: 81,
Name: "Tomato",
}
tomato.Origin = []string{"Mexico", "California"}
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
out, _ := xml.MarshalIndent(nesting, "", " ")
fmt.Println(string(out))
<nesting>
<parent>
<child>
<plant id=“27”>
<name>Coffee</name>
<origin>Ethiopia</origin>
<origin>Brazil</origin>
</plant>
<plant id=“81”>
<name>Tomato</name>
<origin>Mexico</origin>
<origin>California</origin>
</plant>
</child>
</parent>
</nesting>
xml字符串转结构体类型数据
type Plant struct {
XMLName xml.Name `xml:"plant"`
ID int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
func (p Plant) String() string {
return fmt.Sprintf("Plant id=%v, name=%v, origin=%v", p.ID, p.Name, p.Origin)
}
data := []byte(`
<plant id="27">
<name>Coffee</name>
<origin>Ethiopia</origin>
<origin>Brazil</origin>
</plant>
`)
var p Plant
if err := xml.Unmarshal(data, &p); err != nil {
panic(err)
}
fmt.Println(p)
Plant id=27, name=Coffee, origin=[Ethiopia Brazil]