如何将嵌套的XML元素解组到数组中?

问题描述:

我的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 
} 

对于这种嵌套的,你还需要一个结构为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

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

这是一个更好的减少混乱的解决方案,并确认可以正常工作:https://play.golang.org/p/K4WhGBJnfp –

+0

我可以验证这是否正常工作。感谢你的这个@snyh –