在Go语言中,可以定义一个结构体来处理XML文件的所有内部元素。

huangapple go评论79阅读模式
英文:

Define only one struct and have it process all the inner elements of a XML file in Go?

问题

假设我有以下的 XML:

<main symbol="X">
<blockA main_score="3">
    <a score="0"/>
</blockA>
<blockB>
    <b id="3" name="Mike"/>
</blockB>
</main>

我想要定义以下的结构体(空白标签是我想要解决的部分):

type Result struct {
    XMLName xml.Name `xml:"main"`
    Symbol string `xml:"symbol,attr"`
    MainScore int
    Score int
    Id int
    Name string
}

我想要得到的结构体如下:

symbol: X
main_score: 3
score: 0
id: 3
name: Mike

那么我该如何定义 XML 标签来获取内部元素(blockAblockB)以及其属性值(main_score)和内部元素(scoreidname)?

我可以通过定义另外的结构体并将它们嵌入到父结构体 Result 中来解决这个问题。然而,是否仍然有可能不使用嵌入结构体,只在主结构体中定义结构体标签并让它处理整个元素?

谢谢。

英文:

Suppose I have the following xml:

<main symbol="X">
<blockA main_score="3">
    <a score="0"/>
</blockA>
<blockB>
    <b id="3" name="Mike"/>
</blockB>
</main>

And I'd like to define the following struct (blank tags are parts I want to solve):

type Result struct {
    XMLName xml.Name `xml:"main"`
    Symbol string `xml:"symbol,attr"`
    MainScore int
    Score int
    Id int
    Name string
}

And what I'd like to get is the following struct:

symbol: X
main_score: 3
score: 0
id: 3
name: Mike

So how can I define XML tags that goes into inner elements (blockA, blockB) and also reaches its attribute values (main_score) and inner elements (score, id, name)?

I can address the issue here by defining yet another structs and embedding them within the parent Result struct. However, is it still feasible to NOT use the embedding struct and just define struct tags within the main struct and have it process the whole elements?

Thanks.

答案1

得分: 1

我认为目前无法使用当前版本的包将该XML解组为您的结构。

如果支持的话,您可以在MainScore上添加注释:

MainScore int `xml:"blockA>main_score,attr"`

即从blockA子元素中选择main_score属性。然而,目前这种方法不起作用,正如问题3688中所描述的那样。

目前,我认为您需要创建嵌套的结构来完全解组您所需的数据。

英文:

I don't think it is currently possible to unmarshal that XML into your structure with the current version of the package.

If it was supported, you'd want to annotate MainScore with:

MainScore int `xml:"blockA>main_score,attr"`

i.e. pick the main_score attribute from the blockA sub-element. This does not currently work though, as described in issue 3688.

At the moment, I think you will need to create nested structs to fully unmarshal the data you're after.

huangapple
  • 本文由 发表于 2013年9月19日 11:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/18885686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定