XML in Go – how to take either tag and match it to the field of a struct?

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

XML in Go - how to take either tag and match it to the field of a struct?

问题

在Go语言的encoding/xml包中,是否可以将XML文件的任一标签与结构体的字段进行匹配?

例如,在以下XML文件中:

<person>
    <food type="fruit" />
    <furniture type="refrigerator" />
    <food type="vegetable" />
    <food type="fruit" />
<person>

我能否在同一个person字段中按照相应的顺序获取foodfurniture

所以我想要得到的结果如下:

main.Person{main.Food{Type:"fruit"}, main.Furniture{Type:"refrigerator"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}

而不是

main.Person{Food:[]main.Food{main.Food{Type:"fruit"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}, Furniture:[]main.Furniture{main.Furniture{Type:"refrigerator"}}}

这是因为我需要按照时间顺序获取person内的每个项目,而后一个示例仅在每个子标签内对项目进行排序。因此,我无法知道后一个示例中何时出现furniture标签,但可以在前一个示例中获取 - 在这种情况下是第3个。

谢谢。

英文:

Is it feasible to match either tag of a XML file to the field of a struct in encoding/xml package in Go?

For example, in the following XML file:

&lt;person&gt;
    &lt;food type=&quot;fruit&quot; /&gt;
    &lt;furniture type=&quot;refrigerator&quot; /&gt;
    &lt;food type=&quot;vegetable&quot; /&gt;
    &lt;food type=&quot;fruit&quot; /&gt;
&lt;person&gt;

Can I get food and furniture within the same person field with the respective order?

So what I want to get is as follows:

main.Person{main.Food{Type:&quot;fruit&quot;}, main.Furniture{Type:&quot;refrigerator&quot;}, main.Food{Type:&quot;vegetable&quot;}, main.Food{Type:&quot;fruit&quot;}}

instead of

main.Person{Food:[]main.Food{main.Food{Type:&quot;fruit&quot;}, main.Food{Type:&quot;vegetable&quot;}, main.Food{Type:&quot;fruit&quot;}}, Furniture:[]main.Furniture{main.Furniture{Type:&quot;refrigerator&quot;}}}

This is because I have to take each item inside the person as chronological order, and the latter example sorts items only within each sub-tags. So I cannot know when the furniture tag happens in the latter, but can get in the former - 3rd in this case.

Thanks.

答案1

得分: 2

这可能与https://stackoverflow.com/questions/4328867/does-xml-care-about-the-order-of-elements有关。

基本上,如果没有XSD(XML模式定义),你无法指定XML元素的处理或呈现顺序。

如果使用有效的XSD处理XML,可能会起作用。

可以看一下go-xsd

英文:

This is possibly related to https://stackoverflow.com/questions/4328867/does-xml-care-about-the-order-of-elements .

Basically, without an XSD (XML Schema Definition), you can't specify the order that XML elements are processed or presented.

If you process the XML with a valid XSD it may work.

Have a look at go-xsd.

huangapple
  • 本文由 发表于 2013年9月9日 14:26:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/18692554.html
匿名

发表评论

匿名网友

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

确定