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

How do I unmarshal nested XML elements into an array?

我的 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
}

对于这种嵌套,您还需要 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>
type Parent struct {
    Val string
    Children []Child  `xml:"Children>Child"`  //Just use the '>'
}