xml - 如何在 go 中解码 xml 枚举属性?

标签 xml go unmarshalling xml-attribute

我想在 go 中将 xml 属性解析为 iota 枚举类型 (int)。

下面您可以看到我尝试过的方法,但这不起作用,因为无法获取枚举变量的地址。

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

还有其他方法可以使 UnmarshalXMLAttr 与 int 类型一起工作吗?

更新:我知道我可以通过将 UnmarshalXML 方法添加到 Tag 来解决这个问题,但我想尽可能避免这种情况,因为我有很多不同的标签,它们具有很多不同的属性,但只有一个很少有自定义类型的属性。因此,为每个标记实现 UnmarshalXML 方法并不是首选。

最佳答案

我通过将 int 包装在一个结构中解决了这个问题。

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)

是否有“更优雅”的方式,或者我应该对我现在拥有的感到满意?

关于xml - 如何在 go 中解码 xml 枚举属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317781/

相关文章:

java - 如何在 XSLT 2.0 中获取当前 xml 文件名?

c - 为 go 编译的程序禁用堆栈保护

go - 只为接口(interface)传递方法参数一次?

java - JAXB - 忽略元素

java - jaxb 中出现名称冲突时如何收到警告

javascript - 使用 javascript 更改 XML 文件

xml - 限制 for-each 循环 XSL 中排序结果的数量

java - JAXB 解码 <string>foobar</string>

Android:如何识别自定义 XML

go - 如何运行多步 cron 作业,但仍然能够手动执行单个步骤?