Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to parse xml in GO with : in tags

Tags:

xml

go

I find that if tags in XML file have : in them the unmarshal code in Go does not seem to work. Any insights ?

For example, in the XML file below, Summary works but not Cevent.

<summary>...AIR QUALITY ALERT </summary>
<cap:event>Air Quality Alert</cap:event>
type Entry struct{
    Summary    string   `xml:"summary"`
    Cevent     string   `xml:"cap:event"`
}
like image 331
LearnGo Avatar asked Jan 15 '16 21:01

LearnGo


1 Answers

cap is the namespace identifier, not part of the tag name. Here it is shorthand for urn:oasis:names:tc:emergency:cap:1.1

(This answer looks like it may have a good condensed explanation of namespaces: What does "xmlns" in XML mean?)

The Go "encoding/xml" package does not handle namespaces well, but if there are no conflicting tags, you can elide the namespace altogether

type Entry struct {
    Summary string `xml:"summary"`
    Event   string `xml:"event"`
}

The proper way to specify event, especially in the case of identical tags in different namespaces, would be with the full namespace like:

type Entry struct {
    Summary string `xml:"summary"`
    Event   string `xml:"urn:oasis:names:tc:emergency:cap:1.1 event"`
}

Here's a working example: https://play.golang.org/p/ry55F2pWKY

like image 174
JimB Avatar answered Oct 01 '22 06:10

JimB