dousu8767 2016-06-11 18:15
浏览 129

使用Go语言从XML解组数组

Trying to parse xml containing an array using encoding/xml package

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
", 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:""}}}

  • 写回答

1条回答 默认 最新

  • dongpu3898 2016-06-11 19:18
    关注

    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?

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用