Reputation: 35
I can parse complex XML results but I fail at this simple thing which is api returning simple answers like this
xmlFile := <?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
I can't parse TOKEN. I tried everything but can't figure out. I'm using this syntax:
s := strings.Split(string(result),">")
s = strings.Split(s[2],"<")
b.Token = s[0]
<?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
how to parse this (also api returns <?xml version="1.0" encoding="utf-8" standalone="yes"?><ERROR>a error </ERROR>
informations)
Upvotes: 1
Views: 48
Reputation: 38233
For unmarshaling separate top-level elements you can implement a custom unmarshaler.
type Response struct {
Token string
Error string
}
func (r *Response) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
switch start.Name.Local {
case "TOKEN":
if err := d.DecodeElement(&r.Token, &start); err !=nil {
return err
}
case "ERROR":
if err := d.DecodeElement(&r.Error, &start); err !=nil {
return err
}
}
return nil
}
https://play.golang.org/p/OQy4ShS_vFx
Upvotes: 2