I am processing received XML which contains an unordered list of messages where each message can be of one of several distinct types. Order isn't significant.
I have worked out a way to do what I want (after much struggle, this is day 3 of learning go) but am hung up on how to robustly deal with unexpected message types
Here's some code
package main
import (
"encoding/xml"
"fmt"
)
func main() {
data := `<Envelope>
<Body>
<Response>
<Messages>
<Greeting>
<From>Fred</From>
</Greeting>
<Reminder>
<Time>12</Time>
<Subject>Lunch at Joe's</Subject>
</Reminder>
<NewThing>Report me!</NewThing>
<Reminder>
<Time>6</Time>
<Subject>Catch the train</Subject>
</Reminder>
<Greeting>
<From>Mary</From>
<Extra>Hi</Extra>
</Greeting>
</Messages>
<MessageCount>3</MessageCount>
</Response>
</Body>
</Envelope>`
type Greeting struct {
From string
}
type Reminder struct {
Time int
Subject string
}
type TopLevel struct {
Messages struct {
GreetingList []Greeting `xml:"Greeting"`
ReminderList []Reminder `xml:"Reminder"`
} `xml:"Body>Response>Messages"`
}
var reply TopLevel
err := xml.Unmarshal([]byte(data), &reply)
if err != nil {
fmt.Println(err)
return
}
for _, reminder := range reply.Messages.ReminderList {
fmt.Printf("Reminder: '%s' at %d
", reminder.Subject, reminder.Time)
}
for _, greeting := range reply.Messages.GreetingList {
fmt.Printf("Greetings From: %s
", greeting.From)
}
}
The output is
Reminder: 'Lunch at Joe's' at 12
Reminder: 'Catch the train' at 6
Greetings From: Fred
Greetings From: Mary
I would also like to be able to find unexpected types of message that are neither <Greeting>
nor <Reminder>
, such as the <NewThing>
without knowing anything about new things (etc) in advance.
Warning: Unexpected message type: NewThing.
Should I be thinking of some way to have a single list of generic objects? Or using structs of XMLname + innerxml strings somehow? Not sure how to process a single list of such dissimilar types.
Clues?