1 回答
TA贡献1799条经验 获得超9个赞
你是对的,你不能用UnmarshalerAttr这个。相反,ResultItem可以实现Unmarshaler这将允许您设置默认属性值:
package main
import (
"encoding/xml"
"fmt"
)
type ResultItem struct {
Value string `xml:"value,attr"`
Flag bool `xml:"flag,attr"`
}
func (ri *ResultItem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type resultItem ResultItem // new type to prevent recursion
item := resultItem{
Flag: true,
}
if err := d.DecodeElement(&item, &start); err != nil {
return err
}
*ri = (ResultItem)(item)
return nil
}
func main() {
var r struct {
Item[] ResultItem `xml:"item"`
}
xml.Unmarshal([]byte(`
<result x="ASDASD">
<item value="1" flag="false" />
<item value="2" flag="true" />
<item value="3" />
</result>`,
), &r)
fmt.Printf("%+v\n", r)
}
- 1 回答
- 0 关注
- 239 浏览
添加回答
举报