如何将嵌套的XML元素解组成数组?

时间:2016-01-22 07:48:41

标签: xml go unmarshalling

我的XML包含一系列预定义元素,但我无法接收数组。这是XML结构:

var xml_data = `<Parent>
                   <Val>Hello</Val>
                   <Children>
                      <Child><Val>Hello</Val></Child>
                      <Child><Val>Hello</Val></Child>
                      <Child><Val>Hello</Val></Child>
                   </Children>
                </Parent>`

以下是完整代码,这里是playground link。运行它将获取Parent.Val,但不是Parent.Children。

package main

import (
    "fmt"
    "encoding/xml"
)

func main() {

    container := Parent{}
    err := xml.Unmarshal([]byte(xml_data), &container)

    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(container)  
    }
}

var xml_data = `<Parent>
                   <Val>Hello</Val>
                   <Children>
                      <Child><Val>Hello</Val></Child>
                      <Child><Val>Hello</Val></Child>
                      <Child><Val>Hello</Val></Child>
                   </Children>
                </Parent>`

type Parent struct {
    Val string
    Children []Child
}

type Child struct {
    Val string
}

编辑:我将问题简化了一点here。基本上我不能解组任何阵列,而不仅仅是预定义的结构。以下是更新的工作代码。在该示例中,只有一个项目在容器界面中结束。

func main() {

    container := []Child{}
    err := xml.Unmarshal([]byte(xml_data), &container)

    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(container)  
    }

    /* 
        ONLY ONE CHILD ITEM GETS PICKED UP
    */
}

var xml_data = `
            <Child><Val>Hello</Val></Child>
            <Child><Val>Hello</Val></Child>
            <Child><Val>Hello</Val></Child>
        `

type Child struct {
    Val string
}

2 个答案:

答案 0 :(得分:16)

type Parent struct {
    Val string
    Children []Child  `xml:"Children>Child"`  //Just use the '>'
}

答案 1 :(得分:3)

对于这种嵌套,您还需要Children元素的结构:

package main

import (
    "fmt"
    "encoding/xml"
)

func main() {

    container := Parent{}
    err := xml.Unmarshal([]byte(xml_data), &container)

    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(container)  
    }
}

var xml_data = `<Parent>
            <Val>Hello</Val>
            <Children>
                <Child><Val>Hello</Val></Child>
                <Child><Val>Hello</Val></Child>
                <Child><Val>Hello</Val></Child>
            </Children>
        </Parent>`

type Parent struct {
    Val string
    Children Children
}

type Children struct {
    Child []Child
}

type Child struct {
    Val string
}

也粘贴在这里:Go Playground

请注意,您的代码可以使用这种XML结构(在将变量名从Children更改为Child之后):

<Parent>
    <Val>Hello</Val>
    <Child><Val>Hello</Val></Child>
    <Child><Val>Hello</Val></Child>
    <Child><Val>Hello</Val></Child>
</Parent>
相关问题