Reading XML with golang
I am trying to read som XML from golang. I am basing it on this example that works. https://gist.github.com/kwmt/6135123#file-parsetvdb-go
These are my files:
Castle0.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Channel>
<Title>test</Title>
<Description>this is a test</Description>
</Channel>
test.go
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Query struct {
Chan Channel `xml:"Channel"`
}
type Channel struct {
title string `xml:"Title"`
desc string `xml:"Description"`
}
func (s Channel) String() string {
return fmt.Sprintf("%s - %d", s.title, s.desc)
}
func main() {
xmlFile, err := os.Open("Castle0.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
b, _ := ioutil.ReadAll(xmlFile)
var q Query
xml.Unmarshal(b, &q)
fmt.Println(q.Chan)
}
Output: -%! d (string =)
Does anyone know what I am doing wrong? (I do this to learn how to walk, so it's easy on me: P)
source to share
Other packages, including encoding/json
and encoding/xml
, can only see the exported data. So, first yours title
and desc
should be title
and desc
accordingly.
Second, you are using the %d
(integer) format in Sprintf
when you print the string. That's why you get %!d(string=)
what it means "this is not an integer, this is a string!".
Third, there is no request in your XML request, so it automatically binds to q.Chan
.
This is a working example. http://play.golang.org/p/l0ImL2ID-j
source to share