dst8922
dst8922
2016-01-31 03:46

无法使用golang解码XML,始终为空结构

  • xml

I'm trying to decode XML with golang, but the following code gives an empty struct

Anyone can help?

When I run the following code, I always get

{{ packet} []}

Attached source code:

package main

import (
    "fmt"
    "encoding/xml"
//    "io/ioutil"
)

type Field struct {
    XMLName xml.Name `xml:"field"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Proto struct {
    XMLName xml.Name `xml:"proto"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Packet struct {
    XMLName xml.Name `xml:"packet"`
    protos []Proto   `xml:"proto"`
}

func main () {   
    data := []byte(`
<packet>
  <proto name="geninfo" pos="0" showname="General information" size="122">
    <field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
  </proto>
</packet>
    `)

    packet := Packet{}

    err := xml.Unmarshal([]byte(data), &packet)
    if err != nil {
        fmt.Println (err)
        return
    }

    fmt.Println (packet)

    for proto, _ := range (packet.protos) {
        fmt.Println (proto)
    }
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换