英文:
Golang: UnmarshalXMLAttr in encoding/xml
问题
我正在尝试解析一些XML,希望以特殊的方式解析属性。我尝试使用UnmarshalerAttr接口,但无法使其工作。使用以下代码,我只得到了'Castle'的输出。
package main
import (
"encoding/xml"
"fmt"
"strings"
)
type Show struct {
Title string `xml:"Title,attr"`
}
func (s *Show) UnmarshalXMLAttr(attr xml.Attr) error {
fmt.Printf("Parsing attribute '%s', with value '%s'", attr.Name.Local, attr.Value)
s.Title = strings.ToUpper(attr.Value)
return nil
}
func main() {
b := []byte(`<Series Title="Castle"></Series>`)
var show Show
xml.Unmarshal(b, &show)
fmt.Println(show)
}
有什么想法吗?
英文:
I'm trying to unmarshal some XML, where I want to parse the attributes in a special way. I have tried using the UnmarshalerAttr interface but I cannot get it working. Using the following code, the only output I get is '{Castle}'
<!-- language: lang-golang -->
package main
import (
"encoding/xml"
"fmt"
"strings"
)
type Show struct {
Title string `xml:"Title,attr"`
}
func (s *Show) UnmarshalXMLAttr(attr xml.Attr) error {
fmt.Printf("Parsing attribute '%s', with value '%s'", attr.Name.Local, attr.Value)
s.Title = strings.ToUpper(attr.Value)
return nil
}
func main() {
b := []byte(`<Series Title="Castle"></Series>`)
var show Show
xml.Unmarshal(b, &show)
fmt.Println(show)
}
Any ideas?
答案1
得分: 2
属性unmarshaler需要是标题的类型,而不是show的类型。这是修复后的版本:
首先,我们创建一个“伪类型”,它只是包装了字符串并实现了接口。
type title string
现在我们将标题字段定义为我们的类型,而不仅仅是一个字符串。
这将为该属性调用我们的unmarshaler。
type Show struct {
Title title `xml:"Title,attr"`
}
现在是我们类型的自定义unmarshaler:
func (s *title) UnmarshalXMLAttr(attr xml.Attr) error {
fmt.Printf("解析属性'%s',值为'%s'", attr.Name.Local, attr.Value)
*s = title(strings.ToUpper(attr.Value))
return nil
}
其余部分保持不变:
func main() {
b := []byte(`<Series Title="Castle"></Series>`)
var show Show
xml.Unmarshal(b, &show)
fmt.Println(show)
}
http://play.golang.org/p/6J4UZ7BeG1
英文:
The attribute unmarshaler needs to be the type of the title, not the show. here's a fixed version:
First, we create a "faux type" that just wraps string and implements the interface
type title string
Now we define the title field as our type, and not just a string.
This will call our unmarshaler for this attribute
type Show struct {
Title title `xml:"Title,attr"`
}
And now the custom unmashaler for for our type:
func (s *title) UnmarshalXMLAttr(attr xml.Attr) error {
fmt.Printf("Parsing attribute '%s', with value '%s'", attr.Name.Local, attr.Value)
*s = title(strings.ToUpper(attr.Value))
return nil
}
The rest remains the same:
func main() {
b := []byte(`<Series Title="Castle"></Series>`)
var show Show
xml.Unmarshal(b, &show)
fmt.Println(show)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论