1 回答
TA贡献1818条经验 获得超7个赞
基于icza评论的解决方案:
func (b *Book) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
for {
t, err := d.Token()
if err != nil {
if err != io.EOF {
return err
}
return nil
}
switch t := t.(type) {
case xml.StartElement:
var f interface{} // field
var r string // replace
switch t.Name.Local {
case "title":
f = &b.Title
case "author":
if len(b.Author) > 0 { // if "author" was already decoded then assume this is the element in the "blah chardata"
r = b.Author // if you want <author/> to appear in Text then do `r = "<author/>"` instead
} else {
f = &b.Author
}
case "year":
if len(b.Year) > 0 { // same logic as for author above
r = b.Year
} else {
f = &b.Year
}
case "price":
f = &b.Price
}
if f != nil {
if err := d.DecodeElement(f, &t); err != nil {
return err
}
}
if len(r) > 0 {
b.Text += " " + r + " " // add empty space for padding the replacement string
}
case xml.CharData:
s := strings.TrimSpace(string(t))
if len(s) > 0 {
b.Text += s
}
}
}
return nil
}
- 1 回答
- 0 关注
- 65 浏览
添加回答
举报