ds2128629 2013-04-17 18:58
浏览 29
已采纳

golang XML无法正确编组

The XML format I need to unmarshal is as follows:

data := `
<table>
    <name>
        <code>23764</code>
        <name>Smith, Jane</name>
    </name>
    <name>
        <code>11111</code>
        <name>Doe, John</name>
    </name>
</table>
`

I have attempted the following structs and code to no avail:

type Customers struct {

    XMLName xml.Name `xml:"table"`
    Custs []Customer
}

type Customer struct {

    XMLName xml.Name `xml:"name"`
    Code string `xml:"code"`
    Name string `xml:"name"`
}

...

var custs Customers
err := xml.Unmarshal([]byte(data), &custs)
if err != nil {
    fmt.Printf("error: %v", err)
    return
}

fmt.Printf("%v", custs)

for _, cust := range custs.Custs {

    fmt.Printf("Cust:
%v
", cust)
}

The range prints nothing out, and printing custs only gives me {{ table} []}

  • 写回答

1条回答 默认 最新

  • douyou8266 2013-04-17 19:06
    关注

    The correct structure is the following:

    type Customer struct {
        Code string `xml:"code"`
        Name string `xml:"name"`
    }
    
    type Customers struct {
        Customers []Customer `xml:"name"`
    }
    

    You can try it on the playground here. The problem is that you don't assign the xml tag for []Customer.

    The way you solved this, using xml.Name is also correct but more verbose. You can review working code here. If you need to use the xml.Name field for some reason, I would recommend using a private field so that an exported version of the struct is not cluttered.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算