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 關注
- 209 瀏覽
添加回答
舉報