英文:
Parsing Unexpected Fields in XML to a Struct using Go
问题
假设我们有一个XML文档,看起来像这样,在<item>
标签上有一个意外的标签<custom1>
:
<item>
<name>...</name>
<price>...</price>
<custom1>...</custom1>
</item>
用于解析这个XML的结构体如下所示:
type Item struct {
Name string `xml:"name"`
Price string `xml:"price"`
}
由于我没有在结构体中包含Custom1
,因此我不期望它存在。然而,是否有可能捕获剩余的标签或<item>
的原始表示并放入Item
结构体中?
英文:
Lets say we have an XML document that looks like this, which has an unexpected tag <custom1>
on <item>
<item>
<name>...</name>
<price>...</price>
<custom1>...</custom1>
</item>
The struct to parse this looks like this
type Item struct {
Name string `xml:"name"`
Price string `xml:"price"`
}
I don't have Custom1
in there since I'm not expecting it. However, is it possible to capture the remaining tags OR the raw representation of the <item>
inside the Item
struct?
答案1
得分: 2
使用带有,innerxml
标签的字段:
type Item struct {
Name string `xml:"name"`
Price string `xml:"price"`
Other string `xml:",innerxml"`
}
Playground: https://play.golang.org/p/Io2CDjSiwx.
英文:
Use a field with ,innerxml
tag:
type Item struct {
Name string `xml:"name"`
Price string `xml:"price"`
Other string `xml:",innerxml"`
}
Playground: https://play.golang.org/p/Io2CDjSiwx.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论