xml - Go Parse XML to struct by tag 属性

标签 xml go

我正在尝试按属性和值解析以下 XML。

<result name="response" numFound="10775" start="0" maxScore="0.59509283">
    <doc>
        <str name="cui">c0162311</str>
        <str name="display_title">Androgenetic alopecia</str>
        <str name="source">GHR</str>
        <str name="source_url">http://ghr.nlm.nih.gov/condition/androgenetic-alopecia</str>
        <float name="score">0.59509283</float>
    </doc>

我想出了以下内容

type Response struct {
    StrDoc []Str `xml:"result>doc"`
}

type Str struct {
    Doc   []Doc   `xml:"str"`
    Score []Score `xml:"float"`
}

type Doc struct {
    Key   string `xml:"name,attr"`
    Value string `xml:",chardata"`
}

type Score struct {
    Score string `xml:",chardata"`
}

产生

  "StrDoc": [
    {
      "Doc": [
        {
          "Key": "cui",
          "Value": "c0162311"
        },
        {
          "Key": "display_title",
          "Value": "Androgenetic alopecia"
        },
        {
          "Key": "source",
          "Value": "GHR"
        },
        {
          "Key": "source_url",
          "Value": "http://ghr.nlm.nih.gov/condition/androgenetic-alopecia"
        }
      ],
      "Score": [
        {
          "Score": "0.59509283"
        }
      ]
    },

期望的输出是

"Doc": [
            {
              "cui": "c0162311",
              "display_title": "Androgenetic alopecia",
              "source": "GHR",
              "Value": "GHR",
              "source_url": "http://ghr.nlm.nih.gov/",
              "Score": "0.59509283"
            }
          ]

几个小时以来,我一直在努力实现这一目标,但我还没有找到方法。

最佳答案

您可以使用自定义 UnmarshalXML 方法将内部 XML 解码到映射中:

type Result struct {
    Doc Doc `xml:"doc"`
}

type Doc struct {
    Elems map[string]string
}

func (doc *Doc) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) {
    type entry struct {
        Key   string `xml:"name,attr"`
        Value string `xml:",chardata"`
    }
    e := entry{}
    doc.Elems = map[string]string{}
    for err = d.Decode(&e); err == nil; err = d.Decode(&e) {
        doc.Elems[e.Key] = e.Value
    }
    if err != nil && err != io.EOF {
        return err
    }
    return nil
}

Playground :https://play.golang.org/p/87v_vTXpB- .

关于xml - Go Parse XML to struct by tag 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42721278/

相关文章:

mongodb - mongoimport 在 mac Sierra 10.12.2 上抛出随机 MSpanList_Insert 错误

Golang - Web 应用程序中的多个响应值

php - 在 PHP 中使用 SimpleXML 创建带有命名空间的 RSS 元素

android - 布局中的布局 <layout> 在基本布局文件夹中没有声明 [错误]

oracle - 使用 Oracle 调用接口(interface) (OCI) 设置操作系统用户

arrays - channel 元素类型太大 Golang

windows - golang 中的 GetSpecialFolder 等价物

android - 圆形进度条作为 Glide Placeholder

android - 选择器按钮在我的 android 按钮上不起作用。如何解决?

javascript - 使用 NodeJS 构建 XML