我在解码下面的 XML 时遇到问题,如何找到所有 <info>
具有 type="Genres"
的节点并将它们的值存储在 []Genre
中?
<manga id="4199" type="manga" name="Jinki: Extend" precision="manga">
<info type="Main title" lang="EN">Jinki: Extend</info>
<info type="Genres">action</info>
<info type="Genres">science fiction</info>
<info type="Themes">mecha</info>
<info type="Number of tankoubon">9</info>
<info type="Number of pages">186</info>
</manga>
我希望将值存储在类似于以下的结构中:
// Manga struct
type Manga struct {
WorkID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Precision string `xml:"precision,attr"`
Genres []Genre `[this is the part I need help on]`
}
// Genre struct
type Genre struct {
Value string
}
我知道 XML 并不理想,但这是我必须使用的,我希望你们能帮助我。
提前致谢。
最佳答案
自 <manga>
包含 <info>
的列表元素,拥有 Info
列表更有意义结构而不是尝试翻译 <info>
元素分为各种类型。我将定义数据结构,例如:
type Manga struct {
WorkID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Precision string `xml:"precision,attr"`
Info []Info `xml:"info"`
}
type Info struct {
Type string `xml:"type,attr"`
Value string `xml:",chardata"`
}
输出(为了方便而编码的 json)如下所示:
{
"WorkID": 4199,
"Name": "Jinki: Extend",
"Precision": "manga",
"Info": [
{
"Type": "Main title",
"Value": "Jinki: Extend"
},
{
"Type": "Genres",
"Value": "action"
},
{
"Type": "Genres",
"Value": "science fiction"
},
{
"Type": "Themes",
"Value": "mecha"
},
{
"Type": "Number of tankoubon",
"Value": "9"
},
{
"Type": "Number of pages",
"Value": "186"
}
]
}
关于xml - 使用 Go 解码 XML : How to find attributes with the same value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791598/