douqiandai4327 2018-09-28 03:22
浏览 205
已采纳

如何从Golang中的XML文件提取多个字段

Given the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tv SYSTEM "xmltv.dtd">
<zoo>
  <annimal id="1">
    <display-name>hyena</display-name>
  </annimal>
  <annimal id="2">
    <display-name>lion</display-name>
    <icon src="https://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg"/>
  </annimal>
  <annimal id="3">
    <display-name>zebra</display-name>
  </annimal>
</zoo>

what is the simplest way to produce the following output in golang ?

1,hyena
2,lion,https://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg
3,zebra
  • 写回答

1条回答 默认 最新

  • dongzhou4727 2018-09-28 03:44
    关注

    Usually you should at least try something before posting a question on Stack Overflow, but since it's one of your first posts, I don't want to be rude so here's a full answer.

    Using the standard xml library you can do this very easily.

    Here's an example for exactly the behavior you described:

    package main
    
    import (
        "encoding/xml"
        "fmt"
        "log"
    )
    
    type Zoo struct {
        XMLName xml.Name `xml:"zoo"`
    
        Animals []Animal `xml:"animal"`
    }
    
    type Animal struct {
        XMLName xml.Name `xml:"animal"`
        ID      uint     `xml:"id,attr"`
    
        DisplayName DisplayName
        Icon        Icon
    }
    
    type DisplayName struct {
        XMLName xml.Name `xml:"display-name"`
        Value   string   `xml:",chardata"`
    }
    
    type Icon struct {
        XMLName xml.Name `xml:"icon"`
        Source  string   `xml:"src,attr"`
    }
    
    var data []byte = []byte(`
    <zoo>
      <animal id="1">
        <display-name>hyena</display-name>
      </animal>
      <animal id="2">
        <display-name>lion</display-name>
        <icon src="https://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg"/>
      </animal>
      <animal id="3">
        <display-name>zebra</display-name>
      </animal>
    </zoo>`)
    
    func main() {
        var zoo Zoo
        if err := xml.Unmarshal(data, &zoo); err != nil {
            log.Fatal(err)
        }
        for _, animal := range zoo.Animals {
            fmt.Printf("%d,%s,%s
    ", animal.ID, animal.DisplayName.Value, animal.Icon.Source)
        }
    }
    

    Outputs

    1,hyena,
    2,lion,https://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg
    3,zebra,
    

    You can try it out on the Golang Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?