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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)