英文:
golang XML not unmarshal-ing properly
问题
我需要解析的XML格式如下:
data := `
<table>
<name>
<code>23764</code>
<name>Smith, Jane</name>
</name>
<name>
<code>11111</code>
<name>Doe, John</name>
</name>
</table>
`
我尝试了以下结构体和代码,但都没有成功:
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)
}
range循环没有输出任何内容,而打印custs
只给出了{{ table} []}
。
英文:
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:\n%v\n", cust)
}
The range prints nothing out, and printing custs
only gives me {{ table} []}
答案1
得分: 18
正确的结构如下:
type Customer struct {
Code string `xml:"code"`
Name string `xml:"name"`
}
type Customers struct {
Customers []Customer `xml:"name"`
}
您可以在这里的playground上尝试。问题是您没有为[]Customer
分配xml标签。
您解决这个问题的方式,使用xml.Name
也是正确的,但更冗长。您可以在这里查看工作代码。如果您出于某种原因需要使用xml.Name
字段,我建议使用私有字段,以免导出版本的结构变得混乱。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论