xml - Go语言中从xml中解码数组

标签 xml go unmarshalling

尝试使用encoding/xml包解析包含数组的xml

Link to code here

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/

相关文章:

http - 从网址中删除结尾的斜杠-转到静态服务器

Godep 恢复不使用保存在 _workspace 中的代码

java - JaxB 解码 - 创建对象引用

php - 如何使用 SoapClient 将参数传递给函数?

java - 如何使用 JAXB 映射 XML 标记的封闭内容?

c# - 在 ASP.NET MVC 中编写 XML 文件?

go - 如何停止/完成 goroutine

java - 解码、xml 到 java、XSD 中未定义的无效枚举值被忽略

golang中的json解码用于复杂的json数据

XML::LibXML 问题查找具有命名空间的 XML 节点