英文:
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
字段中按照相应的顺序获取food
和furniture
?
所以我想要得到的结果如下:
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:
<person>
<food type="fruit" />
<furniture type="refrigerator" />
<food type="vegetable" />
<food type="fruit" />
<person>
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:"fruit"}, main.Furniture{Type:"refrigerator"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}
instead of
main.Person{Food:[]main.Food{main.Food{Type:"fruit"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}, Furniture:[]main.Furniture{main.Furniture{Type:"refrigerator"}}}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论