du248227 2017-09-15 09:18
浏览 29
已采纳

xml解组后获取根结构

I'm reading an xml file and automatically unmarshalling it.

I defined the data structure as follows:

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"`
}

There is more further down but it doesn't matter for this example.

From an oRow object, I need to access the root oDoc object.

Is this possible? I've seen several examples using interfaces but this seems to require me manually adding each element to set the respective parent. I'm not sure I can do this as the unmarshalling is automatic.

Edit: Example of what I'm trying to achieve. oDoc splits into oTables and oStyles (styles not added for brevity). Each oRow has a style Name corresponding to an oStyle object. I want to be able to create a method that can do

rowOject.getStyleObject()

As per gonutz's suggestion, I could do something like

docObj.getRow(specificRow).getStyle(docObj) 

and use that docObj to drilldown to the style I want but this like it is bad form. If it's the only/best solution, I'll go for it but seems like there should be a better way.

Any suggestions?

  • 写回答

1条回答 默认 最新

  • dongzhuo6137 2017-09-15 10:44
    关注

    Just add back-references to your document if you really need them. Here are the needed changes to the code:

    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
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 无网格伽辽金方法研究裂纹扩展的程序
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题