1 回答
TA贡献1806条经验 获得超5个赞
要处理属性,可以使用UnmarshalerAttr接口与UnmarshalXMLAttr方法。你的例子就变成了:
package main
import (
"encoding/xml"
"fmt"
"strings"
)
type string2 string
type XMLTests struct {
Content string2 `xml:"test_content"`
Tests []*XMLTest `xml:"test_attr>test"`
}
type XMLTest struct {
Name string2 `xml:"name,attr"`
Value string2 `xml:"value,attr"`
}
func decode(s string) string2 {
s = strings.Replace(s, "|", "%7C", -1)
s = strings.Replace(s, "&", "&", -1)
return string2(s)
}
func (s *string2) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var content string
if err := d.DecodeElement(&content, &start); err != nil {
return err
}
*s = decode(content)
return nil
}
func (s *string2) UnmarshalXMLAttr(attr xml.Attr) error {
*s = decode(attr.Value)
return nil
}
func main() {
xmlData := `<?xml version="1.0" encoding="utf-8"?>
<tests>
<test_content>X&amp;Y is a dumb way to write XnY | also here's a pipe.</test_content>
<test_attr>
<test name="Normal" value="still normal" />
<test name="X&amp;Y" value="should be the same as X&Y | XnY would have been easier." />
</test_attr>
</tests>`
xmlFile := strings.NewReader(xmlData)
var q XMLTests
decoder := xml.NewDecoder(xmlFile)
decoder.Decode(&q)
fmt.Println(q.Content)
for _, t := range q.Tests {
fmt.Printf("\t%s\t\t%s\n", t.Name, t.Value)
}
}
输出:
X&Y is a dumb way to write XnY %7C also here's a pipe.
Normal still normal
X&Y should be the same as X&Y %7C XnY would have been easier.
(您可以在Go 操场上进行测试。)
因此,如果string2在任何地方使用都适合您,那么这应该可以解决问题。
(编辑:更简单的代码,不使用DecodeElement和类型开关......)
- 1 回答
- 0 关注
- 185 浏览
添加回答
举报