Dar*_*ren 6 xml go xml-parsing
我需要解组的XML格式如下:
data := `
<table>
<name>
<code>23764</code>
<name>Smith, Jane</name>
</name>
<name>
<code>11111</code>
<name>Doe, John</name>
</name>
</table>
`
Run Code Online (Sandbox Code Playgroud)
我尝试了以下结构和代码无济于事:
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:\n%v\n", cust)
}
Run Code Online (Sandbox Code Playgroud)
范围没有任何打印,打印custs只给我{{ table} []}
nem*_*emo 17
正确的结构如下:
type Customer struct {
Code string `xml:"code"`
Name string `xml:"name"`
}
type Customers struct {
Customers []Customer `xml:"name"`
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里的操场上试试.问题是您没有为其分配xml标记[]Customer.
你解决这个问题的方法,使用xml.Name也是正确的,但更详细.您可以在此处查看工作代码.如果xml.Name由于某种原因需要使用该字段,我建议使用私有字段,以便导出的结构版本不会混乱.
| 归档时间: |
|
| 查看次数: |
8029 次 |
| 最近记录: |