如何从嵌套xml中获取数据,而在重复项中不使用结束标签?

According to the below link, we can get data from nested xml by using > or another struct.

How do I unmarshal nested XML elements into an array?

However it doesn't work in case of not using end tag like this.

code:

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>
                <Child Val="Hello"/>
                <Child Val="Hello"/>
                <Child Val="Hello"/>
        </Parent>`

type Parent struct {
    Val string
    Children Children
}

type Children struct {
    Child []Child
}

type Child struct {
    Val string
}

result:

{Hello {[]}}

Any solution?

<Child> in your XML is a "child" of Parent, so get rid of the Children wrapper struct, the slice should be a field of Parent. Also the values in <Child> are in attributes, so you have to use the ,attr option.

Working model:

type Parent struct {
    Val   string
    Child []Child
}

type Child struct {
    Val string `xml:",attr"`
}

This will output (try it on the Go Playground):

{Hello [{Hello} {Hello} {Hello}]}