Je suis développeur web freelance et propose des formations à Symfony2 ! Contactez-moi pour en discuter.

Parsing XML in Go

21 février, 2017

There is no example about how to use XML with Go on GoByExample, so here is how to do it. We’ll use the encoding/xml package for the standard library.

Let’s imagine the file we want to extract the data from looks like this:

<samples>
    <sample temperature="0.1" iterations="10" />
    <sample temperature="0.5" iterations="1" />
    <sample temperature="1.0" iterations="100" />
</samples>

it has a root node samples, that contains a few nodes of type sample, and these nodes have a bunch of attributes.

We’ll declare 2 structs that will hold these data. First, the sample nodes:

type Sample struct {
    XMLName  xml.Name `xml:"sample"`
    Temperature string `xml:"temperature,attr"`
    Iterations  string `xml:"iterations,attr"`
}

Like for JSON, the properties have metadata that indicate where to look for the data in the XML attributes tree.

Now we’ll do the same for the samples root node:

type Samples struct {
    XMLName  xml.Name `xml:"samples"`
    SampleList []Sample `xml:"sample"`
}

We can now load the data: first we open a file, then the decoder stores the decoded content of the xml file into the requested variable, thus creating the objects on the fly.

// Open file
file, err := os.Open("samples.xml");
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}
defer file.Close()

// Decode file content and store it into a sample variable
var samples Samples
if err := xml.NewDecoder(file).Decode(&samples); err != nil {
    fmt.Println(err)
    os.Exit(1)
}

// Do something with the data
for _, sample := range samples.SampleList {
    fmt.Printf("%s\n", sample)
}

Here is a sample output:


1
2
3
{{ sample} 0.1 10}
{{ sample} 0.5 1}
{{ sample} 1.0 100}

Complete example:

package main

import (
    "fmt"
    "encoding/xml"
    "os"
)

type Sample struct {
    XMLName  xml.Name `xml:"sample"`
    Temperature string `xml:"temperature,attr"`
    Iterations  string `xml:"iterations,attr"`
}

type Samples struct {
    XMLName  xml.Name `xml:"samples"`
    SampleList []Sample `xml:"sample"`
}

func main() {
    // Open file
    file, err := os.Open("samples.xml");
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer file.Close()

    // Decode file content and store it into a sample variable
    var samples Samples
    if err := xml.NewDecoder(file).Decode(&samples); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    // Do something with the data
    for _, sample := range samples.SampleList {
        fmt.Printf("%s\n", sample)
    }
}

Répondre

Unable to load the Are You a Human PlayThru™. Please contact the site owner to report the problem.