dua55014 2019-05-26 22:17
浏览 35

如何在Go中解组xml枚举属性?

I want to parse an xml attribute as an iota enum type (int) in go.

Below you can see what I tried but this does not work because the address of enum variables can't be taken.

type EnumType int
const (
    EnumUnknown EnumType = iota
    EnumFoo
    EnumBar
)

func (E *EnumType) UnmarshalXMLAttr(attr xml.Attr) error {
    switch attr.Value {
    case "foo":
        E = &EnumFoo
    case "bar":
        E = &EnumBar
    default:
        E = &EnumUnknown
    }
    return nil
}


// Example of how the unmarshal could be called:
type Tag struct {
    Attribute EnumType `xml:"attribute,attr"`
}

func main() {
    tag := &Tag{}
    xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
}

Any other way to make UnmarshalXMLAttr work with int types?

Update: I know I can solve this by adding the UnmarshalXML method to Tag but I want to avoid this if possible because I have a lot of different tags with a lot of different attributes but only a few custom typed attributes. So implementing UnmarshalXML methods for each tag would not be preferred.

  • 写回答

1条回答 默认 最新

  • dqg95034 2019-05-27 07:37
    关注

    I solved the problem by wrapping the int in a struct.

    type EnumType int
    const (
        EnumUnknown EnumType = iota
        EnumFoo
        EnumBar
    )
    type EnumContainer struct {
        Value EnumType
    }
    
    func (E *EnumContainer) UnmarshalXMLAttr(attr xml.Attr) error {
        switch attr.Value {
        case "foo":
            E.Value = EnumFoo
        case "bar":
            E.Value = EnumBar
        default:
            E.Value = EnumUnknown
        }
        return nil
    }
    
    
    // Example of how the unmarshal could be called:
    type Tag struct {
        Attribute EnumContainer `xml:"attribute,attr"`
    }
    
    func main() {
        tag := &Tag{}
        xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
    

    Is there a "more elegant" way or should I be happy with what I now have?

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集