如何将XML属性用作struct field?
这是我的测试: 每行对应一个人
package main
import (
"encoding/xml"
"fmt"
)
var xmlstr = `<data>
<row>
<col name='firstname'>John</col>
<col name='age'>2</col>
</row>
<row>
<col name='firstname'>3</col>
<col name='age'>4</col>
</row>
</data>`
type Data struct {
XMLName xml.Name `xml:"data"`
Person []Person `xml:"row"`
}
type Person struct {
PersonField []PersonField `xml:"col"`
}
type PersonField struct {
Name string `xml:"name,attr"`
Value string `xml:",chardata"`
}
func main() {
b := []byte(xmlstr)
var d Data
xml.Unmarshal(b, &d)
for _, person := range d.Person {
fmt.Println(person)
}
}
我选择了2个结构:
{[{firstname John} {age 2}]}
{[{firstname 3} {age 4}]}
我怎样才能获得这个结构?其中xml属性用作结构字段名称?
type Person struct {
Firstname string
Age int
}
答案 0 :(得分:3)
您可以为执行此操作的<row>
元素定义自定义解组,并且#34;解包&#34;为你:
package main
import (
"encoding/xml"
"fmt"
"strconv"
)
var xmlstr = `<data>
<row>
<col name='firstname'>John</col>
<col name='age'>2</col>
</row>
<row>
<col name='firstname'>3</col>
<col name='age'>4</col>
</row>
</data>`
type Data struct {
XMLName xml.Name `xml:"data"`
Person []Person `xml:"row"`
}
type Person struct {
Firstname string
Age int
}
func (p *Person) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
x := struct {
Col []struct {
Name string `xml:"name,attr"`
Value string `xml:",chardata"`
} `xml:"col"`
}{}
err := d.DecodeElement(&x, &start)
if err != nil {
return err
}
for _, col := range x.Col {
switch col.Name {
case "firstname":
p.Firstname = col.Value
case "age":
p.Age, err = strconv.Atoi(col.Value)
if err != nil {
return err
}
}
}
return nil
}
func main() {
b := []byte(xmlstr)
var d Data
if err := xml.Unmarshal(b, &d); err != nil {
panic(err)
}
for _, person := range d.Person {
fmt.Println(person)
}
}