xml - 如何从不在重复项中使用结束标记的嵌套 xml 中获取数据?

标签 xml go struct slice unmarshalling

根据下面的链接,我们可以使用 > 或其他结构从嵌套的 xml 中获取数据。

How do I unmarshal nested XML elements into an array?

但是,如果不使用这样的结束标记,它就不起作用。

代码:

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
}

结果:

{Hello {[]}}

有什么解决办法吗?

最佳答案

<Child>在您的 XML 中是 Parent 的“ child ” , 所以去掉 Children包装器结构, slice 应该是 Parent 的字段.还有 <Child> 中的值在属性中,所以你必须使用 ,attr选项。

工作模型:

type Parent struct {
    Val   string
    Child []Child
}

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

这将输出(在 Go Playground 上尝试):

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

关于xml - 如何从不在重复项中使用结束标记的嵌套 xml 中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56147396/

相关文章:

android - 设置数据绑定(bind)时出现 Kotlin 错误

java - Android 中不显示对话框标题

java - s4s-att-无效值 : Invalid attribute value for 'name' in element 'element'

go - 如何使用 julien schmidt 的路由器避免 Go 中的全局变量?

c - 使用结构体和数组编写函数

c - C 中的嵌套结构/链表

android - XML Android 权限列表完整

html-parsing - 使用 Go lang 从网页中提取链接

http - 发出 http 请求时打开的文件太多

c - 从函数将值分配给全局结构