尝试使用encoding/xml
包解析包含数组的xml
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\n", patient)
}
我无法获取通讯号码。输出结果如下:
main.Patient{Name:main.Name{LastName:"Biscayne", FirstName:"Sophia"}, Gender:"F", CommunicationNumbers:[]main.Communication{main.Communication{Number:"", Qualifier:""}}}
最佳答案
修复非常简单:您必须将路径放在引号中:
CommunicationNumbers []Communication `xml:"CommunicationNumbers>Communication"`
输出(在 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"}}}
事实上,您始终必须将其放在引号中,即使它不是路径而只是 XML 标记名称:
type Communication struct {
Number string `xml:"Number"`
Qualifier string `xml:"Qualifier"`
}
如 reflect.StructTag
的文档中所述,按照惯例,标记字符串的值是空格分隔的 key:"value"
对。 encoding/xml
包通过使用 StructTag.Get()
来使用此约定。方法。如果省略引号,则不会使用您在标记中指定的名称(但将使用字段的名称)。
在此处了解有关结构标记的更多信息:What are the use(s) for tags in Go?
关于xml - Go语言中从xml中解码数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767089/