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

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 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示