How to get a value from an XML using XPath in Go
go, xml, xpath
Solution
Even though not xpath, you can read values out of XML with the native go xml encoder package. You would use the xml.Unmarshal() function. Here is a go play example.
package main
import "fmt"
import "encoding/xml"
func main() {
type People struct {
Names []string `xml:"Person>FullName"`
}
data := `
<People>
<Person>
<FullName>Jerome Anthony</FullName>
</Person>
<Person>
<FullName>Christina</FullName>
</Person>
</People>
`
v := People{Names: []string{}}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("Names of people: %q", v)
}
Problem
Looking at go xml package I could not find such possibility. Go only allows to define tree of structures, map them to XML tree and deserialize using `xml.NewDecoder(myXmlString).Decode(myStruct)`. Even if I define needed tree of Go structures, I still can't query that tree using XPath. C# has convenient function SelectSingleNode that allows to select value from XML tree by specifying XPath without duplicating whole tree structure in C# classes. Is there similar possibility in Go ? If not then what is simplest way to implement it (possibly reusing xml package) ?