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 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误