gpt4 book ai didi

go - 在 xml 解码后获取根结构

转载 作者:IT王子 更新时间:2023-10-29 02:02:46 24 4
gpt4 key购买 nike

我正在读取一个 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 `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 对象。

这可能吗?我见过几个使用接口(interface)的例子,但这似乎需要我手动添加每个元素来设置各自的父元素。我不确定我能否做到这一点,因为解码是自动的。

编辑:我正在努力实现的示例。 oDoc 分为 oTables 和 oStyles(为简洁起见未添加样式)。每个 oRow 都有一个 style Name 对应一个 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
}
}
}

关于go - 在 xml 解码后获取根结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46236071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com