All the examples I found show how to read using unmarshaling functionality into the objects I need to define, but it's quite time consuming as I need to define a lot of staff that I'm not going to use.
Then don't define what you're not going to use, define only what you're going to use. You don't have to create a Go model that perfectly covers the XML structure.
Let's assume you have an XML like this:
<blog id="1234">
<meta keywords="xml,parsing,partial" />
<name>Partial XML parsing</name>
<url>http://somehost.com/xml-blog</url>
<entries count="2">
<entry time="2016-01-19 08:40:00">
<author>Bob</author>
<content>First entry</content>
</entry>
<entry time="2016-01-19 08:30:00">
<author>Alice</author>
<content>Second entry</content>
</entry>
</entries>
</blog>
And let's assume you only need the following info out of this XML:
- id
- keywords
- blog name
- authors names
You can model these wanted pieces of information with the following struct:
type Data struct {
Id string `xml:"id,attr"`
Meta struct {
Keywords string `xml:"keywords,attr"`
} `xml:"meta"`
Name string `xml:"name"`
Authors []string `xml:"entries>entry>author"`
}
And now you can parse only these information with the following code:
d := Data{}
if err := xml.Unmarshal([]byte(s), &d); err != nil {
panic(err)
}
fmt.Printf("%+v", d)
Output (try it on the Go Playground):
{Id:1234 Meta:{Keywords:xml,parsing,partial} Name:Partial XML parsing Authors:[Bob Alice]}