登录
首页 >  Golang >  Go问答

解组 XML:根据属性值使用不同的目标类型

来源:stackoverflow

时间:2024-04-29 18:18:35 353浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《解组 XML:根据属性值使用不同的目标类型》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我想使用不同的类型根据其父节点的名称属性来解组子节点的 xml 内容。

在下面的示例中,我有 2 个具有属性“apple”和“peach”的子节点。当属性为 "apple" 时,我想使用 apple 类型;当属性为 "peach" 时,我想使用 peach 类型。基本上 applepeach 具有非常不同的结构,所以这就是场景。我将如何实现这一点或建议的方法是什么?

这是包含问题基本设置的演示。

<element>
    <node name="apple">
        <apple>
            <color>red<color>
        </apple>
    </node>
    <node name="peach"> 
        <peach>
            <size>medium</size>
        </peach>
    </node>
</element>
var x = `...` // xml
type Element struct {
    Nodes []struct{
        Name string `xml:"name,attr"`
    } `xml:"node"`
    Apple Apple
    Peach Peach
}
type Apple struct { // use this struct if name is "apple"
    Color string 
} 
type Peach struct { // use this struct if name is "peach"
    Size string
}
func main() {
    e := Element{}
    err := xml.Unmarshal([]byte(x), &e)
    if err != nil {
        panic(err)
    }   
    fmt.Println(e.Apple.Color)
    fmt.Println(e.Peach.Size
}

解决方案


您可以简单地迭代 element 类型的节点,并通过打开 name 属性来创建 applepeach 结构:

    for _, element := range e.nodes {
        switch element.name {
        case "apple":
            apples = append(apples, apple{})
        case "peach":
            peaches = append(peaches, peach{})
        }
    }

Here is a playground link

另一个更复杂的解决方案(但也更优雅和实用)是在 element 类型上实现您自己的 unmarshalxml 方法,这将直接用正确的类型填充它:

type apple struct {
    color string
}
type peach struct {
    size string
}

type fruits struct {
    apples  []apple
    peaches []peach
}

type element struct {
    xmlname xml.name `xml:"element"`
    nodes   []struct {
        name  string `xml:"name,attr"`
        apple struct {
            color string `xml:"color"`
        } `xml:"apple"`
        peach struct {
            size string `xml:"size"`
        } `xml:"peach"`
    } `xml:"node"`
}

func (f *fruits) unmarshalxml(d *xml.decoder, start xml.startelement) error {
    var element element
    d.decodeelement(&element, &start)

    for _, el := range element.nodes {
        switch el.name {
        case "apple":
            f.apples = append(f.apples, apple{
                color: el.apple.color,
            })
        case "peach":
            f.peaches = append(f.peaches, peach{
                size: el.peach.size,
            })
        }
    }

    return nil
}

func main() {
    f := fruits{}

    err := xml.unmarshal([]byte(x), &f)
    if err != nil {
        panic(err)
    }

    fmt.println("apples:", f.apples)
    fmt.println("peaches", f.peaches)
}

Here is a playground link for this second solution

结果:

Apples: [{red}]
Peaches [{medium}]

以上就是《解组 XML:根据属性值使用不同的目标类型》的详细内容,更多关于的资料请关注golang学习网公众号!

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