trouble parsing XML with embedded structs

69 views
Skip to first unread message

Lars R. Damerow

unread,
Jun 4, 2020, 2:06:50 PM6/4/20
to golan...@googlegroups.com
Hello all,

I need to parse XML messages from a source I don't control. Each one has an envelope node that shows its source, and the first node in that envelope encodes the message type. I'm trying to compose structs to make it easier to do the parsing, and I put a stripped-down example for just one message type on the playground here:

https://play.golang.org/p/tszPHRM-mMO

What's puzzling me here is that, after unmarshaling, `v.Envelope.XMLName.Local` is empty. I'd expect it to contain "proto-alpha" from the example XML in the source; it does pick up the version attribute that's set on the envelope node, just not the `xml.Name` value.

Can anyone share some clues about what I'm doing wrong here?

Thanks very much,
-lars

--
lars r. damerow

https://keybase.io/ldamerow
F29F 160D B23C 3237 1BA3 FCD5 4E13 C775 36B3 ABCA

Ain

unread,
Jun 6, 2020, 3:37:09 AM6/6/20
to golang-nuts
On Thursday, June 4, 2020 at 9:06:50 PM UTC+3, Lars R. Damerow wrote:
Hello all,

I need to parse XML messages from a source I don't control. Each one has an envelope node that shows its source, and the first node in that envelope encodes the message type. I'm trying to compose structs to make it easier to do the parsing, and I put a stripped-down example for just one message type on the playground here:

https://play.golang.org/p/tszPHRM-mMO

What's puzzling me here is that, after unmarshaling, `v.Envelope.XMLName.Local` is empty. I'd expect it to contain "proto-alpha" from the example XML in the source; it does pick up the version attribute that's set on the envelope node, just not the `xml.Name` value.

Can anyone share some clues about what I'm doing wrong here?

You have a extra layer there in the structs, try this

type Envelope struct {
    XMLName xml.Name
    Version string `xml:"version,attr"`
    Body GreetingBody
}

type GreetingBody struct {
    XMLName xml.Name `xml:"greeting"`
    Str     string   `xml:"str"`
}


func main() {
    var input = `<?xml version ="1.0" encoding="UTF-8"?>
<proto-alpha version="1.3">
  <greeting>
     <str>hello</str>
  </greeting>
</proto-alpha>
`
    v := Envelope{}
    if err := xml.Unmarshal([]byte(input), &v); err != nil {
        log.Panic(err)
    }
   
    fmt.Printf("%+v\n", v)
}

HTH
ain
Reply all
Reply to author
Forward
0 new messages