douqiandai4327
2018-09-28 03:22
浏览 198

如何从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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题