2016-01-22 115 views
1

我的XML包含一個預定義元素的數組,但我無法拿起數組。下面是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 
} 

回答

2

對於這種嵌套的,你還需要一個結構爲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

請注意,您的代碼將工作(改變變量之後名稱從ChildrenChild)與這種XML結構:

<Parent> 
    <Val>Hello</Val> 
    <Child><Val>Hello</Val></Child> 
    <Child><Val>Hello</Val></Child> 
    <Child><Val>Hello</Val></Child> 
</Parent> 
+0

謝謝。您能否告訴我從我的編輯中看到簡化示例中的樣子?我正在應用您的解決方案,但不起作用。這裏是操場:https://play.golang.org/p/cXG6prczVK – believesInSanta

+0

根據你解釋的原則,第一個例子應該工作 – believesInSanta

+0

我相信在這種情況下,問題可能是,XML必須只有一個頂部-level元素 - 即你的XML輸入在第二個例子中是無效的XML – petrkotek

8
type Parent struct { 
    Val string 
    Children []Child `xml:"Children>Child"` //Just use the '>' 
} 
+2

這是一個更好的減少混亂的解決方案,並確認可以正常工作:https://play.golang.org/p/K4WhGBJnfp –

+0

我可以驗證這是否正常工作。感謝你的這個@snyh –