duanaoreng9355 2019-06-17 05:41
浏览 54
已采纳

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

I want to use a different type to unmarshal the XML content of a child node based on its parent's name attribute.

In the following example I have 2 children nodes with attributes "apple" and "peach". I would like to use type Apple when the attribute is "apple" and Peach when it's "peach". Basically Apple and Peach have very different structures, so that's the scenario. How would I accomplish that or what would be the suggested approach?

Here is the playground with a basic setup to the problem.

<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
}
  • 写回答

1条回答 默认 最新

  • doujingxi3356 2019-06-17 05:58
    关注

    You can simply iterate on the nodes of your Element type and create the Apple and Peach structures as you go, by switching on their Name attribute:

        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.

    Another, more complex solution (but also more elegant and practical) would be to implement your own UnmarshalXML method on your Element type, which would directly populate it with the proper types:

    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

    Result:

    Apples: [{red}]
    Peaches [{medium}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况