亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將嵌套的 XML 元素解組為數組?

如何將嵌套的 XML 元素解組為數組?

Go
慕勒3428872 2021-12-07 15:03:06
我的 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>`這是完整的代碼,這是操場鏈接。運行此命令將獲取 Parent.Val,但不會獲取 Parent.Children。package mainimport (    "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}編輯:我在這里稍微簡化了這個問題。基本上我不能解組任何數組,而不僅僅是預定義的結構。以下是更新后的工作代碼。在該示例中,只有一項最終出現在容器界面中。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 回答

?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

type Parent struct {

    Val string

    Children []Child  `xml:"Children>Child"`  //Just use the '>'

}


查看完整回答
反對 回復 2021-12-07
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

對于這種嵌套,您還需要一個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

}

也貼在這里:去游樂場


請注意,您的代碼可以使用這種 XML 結構(在將變量名從 更改Children為 之后Child):


<Parent>

    <Val>Hello</Val>

    <Child><Val>Hello</Val></Child>

    <Child><Val>Hello</Val></Child>

    <Child><Val>Hello</Val></Child>

</Parent>


查看完整回答
反對 回復 2021-12-07
  • 2 回答
  • 0 關注
  • 273 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號