dsgwoh7038 2016-06-11 16:14
浏览 216

如何使用Go语言中的encoding / xml包获取xml属性值

I need to convert following xml to go struct.

https://play.golang.org/p/tboi-mp06k

var data = `<Message xmlns="http://www.ncpdp.org/schema/SCRIPT"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     release="006"
     version="010">`

type Message struct {
   XMLName  xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
   release string `xml:"release,attr"`
   version string `xml:"version,attr"`
}

func main() {

    msg := Message{}
    _ = xml.Unmarshal([]byte(data), &msg)   

   fmt.Printf("%#v
", msg)

}

Program outputs the following: main.Message{XMLName:xml.Name{Space:"http://www.ncpdp.org/schema/SCRIPT", Local:"Message"}, release:"", version:""} release and version are empty. Any suggestions please?

  • 写回答

1条回答 默认 最新

  • dongxun5349 2016-06-11 19:20
    关注

    Changing your struct to:

    type Message struct {
       XMLName  xml.Name `xml:http://www.ncpdp.org/schema/SCRIPT "Message"`
       Release string `xml:"release,attr"`
       Version string `xml:"version,attr"`
    }
    

    will solve the issue. Go uses case to determine whether a particular identifier is public or private within the context of your package. In your code, the fields are not visible to xml.Unmarshal because it is not part of the package containing your code.

    When you change the fields to be upper case, they became public so could be exported.

    Working Example : https://play.golang.org/p/h8Q4t_3ctS

    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。