【问题标题】:How can I get data from nested xml which doesn't use end tag in repeat items?如何从嵌套的 xml 中获取数据,该数据在重复项中不使用结束标记?
【发布时间】:2019-05-15 10:41:19
【问题描述】:

根据下面的链接,我们可以使用>或其他结构从嵌套的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 {[]}}

有什么办法吗?

【问题讨论】:

    标签: xml go struct slice unmarshalling


    【解决方案1】:

    您的 XML 中的&lt;Child&gt;Parent 的“子”,所以去掉Children 包装结构,切片应该是Parent 的字段。 &lt;Child&gt; 中的值也在属性中,所以你必须使用,attr 选项。

    工作模式:

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

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

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

    【讨论】:

    • 真丢脸。谢谢 !结束标签与我的错误无关。 ,attr也是重点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-05-18
    • 2015-01-11
    • 2014-04-09
    • 1970-01-01
    • 2015-08-04
    相关资源
    最近更新 更多