package main import ( "encoding/xml" "fmt" ) type person struct { Name string `xml:"name,attr"` Age int `xml:"年龄"` } func main() { p := person{Name: "sary", Age: 18} var data []byte var err error if data, err = xml.MarshalIndent(p, "", " "); err != nil { fmt.Println(err) return } else { fmt.Println(string(data)) } p2 := new(person) if err = xml.Unmarshal(data, p2); err != nil { fmt.Println(err) return } else { fmt.Println(p2) } }
输出:
<person name="sary"> <年龄>18</年龄> </person> &{sary 18}
注意: flag对于需要同名的多个参数则不适合(可将多个同名的参数作为一个字串参数,再自行截取再配对)
属性自定义:`xml:"name,attr"`
package main import ( "encoding/xml" "fmt" ) type Person struct { Name string `xml:"name,attr"` Age int } func main() { p := Person{Name: "sary", Age: 30} var data []byte var err error if data, err = xml.MarshalIndent(p, "", " "); err != nil { fmt.Println(err) return } else { fmt.Println(string(data)) } p2 := new(Person) if err = xml.Unmarshal(data, p2); err != nil { fmt.Println(err) return } else { p2.Age = 18 fmt.Println(p2) } }