登录
首页 >  Golang >  Go问答

Go 中如何解析包含 xml 枚举属性的数据?

来源:stackoverflow

时间:2024-03-21 09:36:28 206浏览 收藏

在 Go 中,要将 XML 属性解析为 iota 枚举类型,可以采用包装 int 类型的结构体方式。具体方法是创建一个 EnumType 枚举类型,然后定义一个 EnumContainer 结构体,将 EnumType 类型的值封装在其中。通过为 EnumContainer 结构体实现 UnmarshalXMLAttr 方法,可以根据 XML 属性值设置 EnumType 的值。这种方法避免了为每个标签实现 UnmarshalXML 方法的繁琐操作,且适用于拥有不同标签和属性的数据解析场景。

问题内容

我想在 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)
}

还有其他方法可以使 unmarshalxmlattr 使用 int 类型吗?

更新:我知道我可以通过向标签添加 unmarshalxml 方法来解决这个问题,但我想尽可能避免这种情况,因为我有很多不同的标签,它们有很多不同的属性,但只有一些自定义类型的属性。因此,为每个标签实现 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)

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>