1

I'm trying to decode XML with golang, but the following code gives an empty struct

Anyone can help?

When I run the following code, I always get

{{ packet} []}

Attached source code:

package main

import (
    "fmt"
    "encoding/xml"
//    "io/ioutil"
)

type Field struct {
    XMLName xml.Name `xml:"field"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Proto struct {
    XMLName xml.Name `xml:"proto"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Packet struct {
    XMLName xml.Name `xml:"packet"`
    protos []Proto   `xml:"proto"`
}

func main () {   
    data := []byte(`
<packet>
  <proto name="geninfo" pos="0" showname="General information" size="122">
    <field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
  </proto>
</packet>
    `)

    packet := Packet{}

    err := xml.Unmarshal([]byte(data), &packet)
    if err != nil {
        fmt.Println (err)
        return
    }

    fmt.Println (packet)

    for proto, _ := range (packet.protos) {
        fmt.Println (proto)
    }
}

1 Answer 1

4

You need to export your struct fields as per https://golang.org/pkg/encoding/xml/#Unmarshal

Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.

e.g.

type Proto struct {
    XMLName xml.Name `xml:"field"`
    Name      string `xml:"name,attr"`
    Shownameg string `xml:"showname,attr"`
    Fields []Field
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.