tjoe
tjoe

Reputation: 63

How to extract multiple fields from a XML file in golang

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

Upvotes: 1

Views: 459

Answers (1)

Ullaakut
Ullaakut

Reputation: 3734

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\n", 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

Upvotes: 1

Related Questions