我正在尝试解析一个类似以下的XML文件 - (请注意实际文件还有许多其他标签,我能够成功解析)
<process name="p" id="1234">
<app>
<element name="ele-1">
<id>84594</id>
<element name="ele-11">
<id>95065</id>
<element name="ele-111">
<id>5065</id>
</element> //ele-111
</element> //ele-11
<element name="ele-12">
<id>4954</id>
</element> //ele-12
</element>//ele-1
</app>
.
.
.
//Many other tags here which are working fine
</process>
我已经添加了ele-#
,这样就容易看到一个元素的起始和结束位置。一旦我们进入最上面的元素(ele-1),这些嵌套元素可能会不断地嵌套下去。
这意味着ele-1将有一系列嵌套元素,每个元素可能有也可能没有一系列嵌套元素,然后每个元素又可以有或没有...
我想在Go语言中解析这个结构。最好的方法是什么?
我已经定义了类似于这样的东西:
type ProcessDef struct {
Process xml.Name `xml:"process"`
Name string `xml:"name,attr"`
Id string `xml:"id,attr"`
App AppDef `xml:"app"`
}
type AppDef struct {
App xml.Name `xml:"app"`
Elements []ElementDef `xml:"element"`
}
type ElementDef struct {
Element xml.Name `xml:"element"`
Name string `xml:"name,attr"`
Id string `xml:"id"`
Elements []ElementDef
}
尽管我在解析XML时能够读取和填充AppDef结构中第一个(顶级)元素的值,但无法使用ElementDef结构中嵌套的递归定义解析并获取所有子元素的值。
另外,当我尝试在ElementDef结构的切片字段上添加xml注释,例如 - Elements []ElementDef xml:"element"时,会收到警告:struct field Elements repeats xml tag "element"。
我有点迷失在如何以最佳方式在Go中解析此类XML文档。