I’m exploring “encoding/xml”‘s Unmarshal function to get a better understanding of its features.
An Unmarshaling scenario I’ve been looking at is to create a proper golang struct to parse an XML snippet that looks like:
<ASSEMBLY>
<COMMON>Build 37</COMMON>
<STANDARD short_name="GRCh37-lite"/>
</ASSEMBLY>
I’ve been able to successfully the above XML using two structures, described below ( and in http://play.golang.org/p/RiI422j163 ):
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type Standard struct {
ShortName string `xml:"short_name,attr"`
}
type Assembly struct {
XMLName xml.Name `xml:"ASSEMBLY"`
Common string `xml:"COMMON"`
Std Standard `xml:"STANDARD"`
}
var v Assembly
data := `
<ASSEMBLY>
<COMMON>Build 37</COMMON>
<STANDARD short_name="GRCh37-lite"/>
</ASSEMBLY>
`
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v\n", v)
}
However, I’m only interested in parsing just value of the COMMON element and the “short_name” attribute on the STANDARD element.
Is there a way I could elegantly Unmarshal my interesting elements of the XML directly into a single struct like
type Assembly struct {
XMLName xml.Name `xml:"ASSEMBLY"`
Common string
ShortName string
}
?
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Many Thanks for providing illustrative examples for both approaches! I was also looking at Francesc Campoy’s recent presentation: JSON, interfaces and go generate. Although it is about JSON, the unmarshaling ideas given in the presentation seem similar to what both of you have suggested for XML unmarshaling.