英文:
Golang marshal dynamic xml element name
问题
XML文件由两个元素组成。这些元素具有相同的结构,除了一个元素名称不同。我尝试设置XMLName属性的值,但没有成功。
XML:
<!-- 第一个元素 -->
<PERSON>
<ELEM1>...</ELEM1>
<ELEM2>...</ELEM2>
<ELEM3>...</ELEM3>
<ELEM4>...</ELEM4>
</PERSON>
<!-- 第二个元素 -->
<SENDER>
<ELEM1>...</ELEM1>
<ELEM2>...</ELEM2>
<ELEM3>...</ELEM3>
<ELEM4>...</ELEM4>
</SENDER>
是否可以定义一个结构体,使元素名称是动态的?
type Person struct {
XMLName string `xml:"???"` // 如何使其动态?
e1 string `xml:"ELEM1"`
e2 string `xml:"ELEM2"`
e3 string `xml:"ELEM3"`
e4 string `xml:"ELEM4"`
}
英文:
The xml file consists of two elements. Those elements have the same structure except for one element name. I tried to set a value to the XMLName property, but that didn't work.
Xml:
<!-- first element -->
<PERSON>
<ELEM1>...</ELEM1>
<ELEM2>...</ELEM2>
<ELEM3>...</ELEM3>
<ELEM4>...</ELEM4>
</PERSON>
<!-- second element -->
<SENDER>
<ELEM1>...</ELEM1>
<ELEM2>...</ELEM2>
<ELEM3>...</ELEM3>
<ELEM4>...</ELEM4>
</SENDER>
Is it possible to define a struct such that the element name is dynamic?
type Person struct {
XMLName string `xml:"???"` // How make this dynamic?
e1 string `xml:"ELEM1"`
e2 string `xml:"ELEM2"`
e3 string `xml:"ELEM3"`
e4 string `xml:"ELEM4"`
}
答案1
得分: 10
在文档中,它说XMLName
字段必须是xml.Name
类型。
type Person struct {
XMLName xml.Name
E1 string `xml:"ELEM1"`
// ...
}
通过xml.Name
的Local
字段设置元素名称:
person := Person {
XMLName: xml.Name { Local: "Person" },
// ...
}
(另外,为了将其包含在XML输出中,E1 - E4必须是可导出的)。
Playground示例:http://play.golang.org/p/bzSutFF9Bo
英文:
In the documentation, it says that the XMLName
field must be of type xml.Name
.
type Person struct {
XMLName xml.Name
E1 string `xml:"ELEM1"`
// ...
}
Set the element name via the Local
field of xml.Name
:
person := Person {
XMLName: xml.Name { Local: "Person" },
// ...
}
(Also, E1 - E4 must be exported in order to be included in the XML output).
Playground example: http://play.golang.org/p/bzSutFF9Bo
答案2
得分: 3
我找到了一个更简洁的解决方案,你只需要像这样为XMLName
字段设置结构标签:
type Person struct {
XMLName xml.Name `xml:"Person"`
E1 string `xml:"ELEM1"`
// ...
}
英文:
I found a lighter solution for this case where you only need to set the struct tag for XMLName
field like this:
type Person struct {
XMLName xml.Name `xml:"Person"`
E1 string `xml:"ELEM1"`
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论