Golang:编码/ xml中的UnmarshalXMLAttr

时间:2014-07-27 10:46:41

标签: xml go unmarshalling

我试图解组一些XML,我想以特殊的方式解析属性。我尝试过使用UnmarshalerAttr interface,但我无法使用它。使用以下代码,我得到的唯一输出是' {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)
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

属性unmarshaler需要是标题的类型,而不是节目。这是一个固定版本:

首先,我们创造一个&#34; faux type&#34;只是包装字符串并实现接口

type title string

现在我们将标题字段定义为我们的类型,而不仅仅是字符串。

这会调用我们的unmarshaler来获取此属性

type Show struct {
    Title title `xml:"Title,attr"`
}

现在我们的类型的自定义unmashaler:

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
}

其余的保持不变:

func main() {

    b := []byte(`<Series Title="Castle"></Series>`)

    var show Show
    xml.Unmarshal(b, &show)

    fmt.Println(show)
}

http://play.golang.org/p/6J4UZ7BeG1