douzhuo3233 2014-07-27 10:46
浏览 96
已采纳

Golang:encoding / xml中的UnmarshalXMLAttr

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}'

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条回答 默认 最新

  • dongzi1397 2014-07-27 10:58
    关注

    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)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?