Go 在xml解组后获取根结构
我正在读取一个xml文件并自动将其解组 我对数据结构的定义如下:Go 在xml解组后获取根结构,go,unmarshalling,Go,Unmarshalling,我正在读取一个xml文件并自动将其解组 我对数据结构的定义如下: type oDoc struct { Body oBody `xml:"body"` AutoStyle oAutoStyle `xml:"automatic-styles"` } type oBody struct { Spreadsheet oSpread `xml:"spreadsheet"` } type oSpread struct { Tables []oTable
type oDoc struct {
Body oBody `xml:"body"`
AutoStyle oAutoStyle `xml:"automatic-styles"`
}
type oBody struct {
Spreadsheet oSpread `xml:"spreadsheet"`
}
type oSpread struct {
Tables []oTable `xml:"table"`
}
type oTable struct {
Name string `xml:"name,attr"`
Rows []oRow `xml:"table-row"`
}
type oRow struct {
Cells []oCell `xml:"table-cell"`
Style string `xml:"style-name,attr"`
}
下面还有更多,但对于这个例子来说并不重要
从oRow对象,我需要访问根oDoc对象
这可能吗?我见过几个使用接口的示例,但这似乎需要我手动添加每个元素来设置相应的父元素。我不确定我能不能这样做,因为解组是自动的
编辑:我试图实现的示例。oDoc分为Otable和Ostyle(为简洁起见未添加样式)。每个oRow都有一个与oStyle对象相对应的样式名。我希望能够创建一个可以
rowOject.getStyleObject()
根据gonutz的建议,我可以做如下事情
docObj.getRow(specificRow).getStyle(docObj)
使用docObj深入到我想要的样式,但这是一种糟糕的形式。如果这是唯一/最好的解决方案,我会去的,但似乎应该有更好的办法
有什么建议吗?如果您确实需要,只需在文档中添加引用即可。以下是对代码所需的更改:
type oRow struct {
Cells []oCell `xml:"table-cell"`
Style string `xml:"style-name,attr"`
doc *oDoc // this will not affect the xml parsing
}
func main() {
var doc oDoc
// load the oDoc...
// then add the back-references
for t := range doc.Body.Spreadsheet.Tables {
table := &doc.Body.Spreadsheet.Tables[t]
for i := range table.Rows {
table.Rows[i].doc = &doc
}
}
}
所以你把
oDoc
解封了,对吗?这意味着您知道其中包含的所有内容。我建议简单地重新构造代码,将相应的oDoc
传递到处理oRow
的相同位置?是的,我也这么想,但选择不这样做。这需要在同一行中调用两次oDoc对象,必须有更好的方法来实现这一点。在原始问题中添加了我的用例的具体示例,您似乎无法在注释中输入代码,因此我将我的重播作为答案。@gonutz这确实有效,非常感谢。