Trying to parse xml containing an array using encoding/xml
package
import (
"fmt"
"encoding/xml"
)
var data = `
<Patient>
<Name>
<LastName>Biscayne</LastName>
<FirstName>Sophia</FirstName>
</Name>
<Gender>F</Gender>
<CommunicationNumbers>
<Communication>
<Number>9415551223</Number>
<Qualifier>TE</Qualifier>
</Communication>
<Communication>
<Number>4055559999</Number>
<Qualifier>TE</Qualifier>
</Communication>
</CommunicationNumbers>
</Patient>
`
type Name struct {
LastName string
FirstName string
}
type Communication struct {
Number string `xml:Number`
Qualifier string `xml:Qualifier`
}
type Patient struct {
Name Name
Gender string
CommunicationNumbers []Communication `xml:CommunicationNumbers>Communication`
}
func main() {
patient := Patient{}
_ = xml.Unmarshal([]byte(data), &patient)
fmt.Printf("%#v
", patient)
}
I am not able to get communication numbers. The output is as follows:
main.Patient{Name:main.Name{LastName:"Biscayne", FirstName:"Sophia"}, Gender:"F", CommunicationNumbers:[]main.Communication{main.Communication{Number:"", Qualifier:""}}}
Fix is really easy: you have to put the path in quotes:
CommunicationNumbers []Communication `xml:"CommunicationNumbers>Communication"`
Output (try it on the Go Playground):
main.Patient{Name:main.Name{LastName:"Biscayne", FirstName:"Sophia"}, Gender:"F", CommunicationNumbers:[]main.Communication{main.Communication{Number:"9415551223", Qualifier:"TE"}, main.Communication{Number:"4055559999", Qualifier:"TE"}}}
In fact you always have to put it in quotes, even if it is not a path but just an XML tag name:
type Communication struct {
Number string `xml:"Number"`
Qualifier string `xml:"Qualifier"`
}
As mentioned in the documentation of reflect.StructTag
, by convention the value of a tag string is a space-separated key:"value"
pairs. The encoding/xml
package uses this convention by using the StructTag.Get()
method. If you omit the quotes, the name you specify in the tag will not be used (but the name of the field will be used).
Read more about struct tags here: What are the use(s) for tags in Go?