xml - 使用 Go 解码 XML : How to find attributes with the same value?

标签 xml go

我在解码下面的 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/

相关文章:

java - 使用 Jetty maven 插件部署 war

java - RecyclerView 中的网格项未正确显示

datetime - 如何在不解析表行的情况下更改结构上的日期格式(如 "yyyy-mm-dd")?

golang windows服务失败,没有任何错误

go - 限制变量存储错误的范围

python - 如何让 Python XMLGenerator 输出 CDATA

android - 自定义命名空间支持库 ActionBar?

java - 如何编写有文件大小限制的XML?

go - 无法设置 Cookie。

go - 为什么使用 Go interface{} 作为参数,当我用字符串调用 func 时,它会强制转换一个 alloc/ns?