golang XML未正确解组

huangapple go评论105阅读模式
英文:

golang XML not unmarshal-ing properly

问题

我需要解析的XML格式如下:

  1. data := `
  2. <table>
  3. <name>
  4. <code>23764</code>
  5. <name>Smith, Jane</name>
  6. </name>
  7. <name>
  8. <code>11111</code>
  9. <name>Doe, John</name>
  10. </name>
  11. </table>
  12. `

我尝试了以下结构体和代码,但都没有成功:

  1. type Customers struct {
  2. XMLName xml.Name `xml:"table"`
  3. Custs []Customer
  4. }
  5. type Customer struct {
  6. XMLName xml.Name `xml:"name"`
  7. Code string `xml:"code"`
  8. Name string `xml:"name"`
  9. }
  10. ...
  11. var custs Customers
  12. err := xml.Unmarshal([]byte(data), &custs)
  13. if err != nil {
  14. fmt.Printf("error: %v", err)
  15. return
  16. }
  17. fmt.Printf("%v", custs)
  18. for _, cust := range custs.Custs {
  19. fmt.Printf("Cust:\n%v\n", cust)
  20. }

range循环没有输出任何内容,而打印custs只给出了{{ table} []}

英文:

The XML format I need to unmarshal is as follows:

  1. data := `
  2. <table>
  3. <name>
  4. <code>23764</code>
  5. <name>Smith, Jane</name>
  6. </name>
  7. <name>
  8. <code>11111</code>
  9. <name>Doe, John</name>
  10. </name>
  11. </table>
  12. `

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

  1. type Customers struct {
  2. XMLName xml.Name `xml:"table"`
  3. Custs []Customer
  4. }
  5. type Customer struct {
  6. XMLName xml.Name `xml:"name"`
  7. Code string `xml:"code"`
  8. Name string `xml:"name"`
  9. }
  10. ...
  11. var custs Customers
  12. err := xml.Unmarshal([]byte(data), &custs)
  13. if err != nil {
  14. fmt.Printf("error: %v", err)
  15. return
  16. }
  17. fmt.Printf("%v", custs)
  18. for _, cust := range custs.Custs {
  19. fmt.Printf("Cust:\n%v\n", cust)
  20. }

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

答案1

得分: 18

正确的结构如下:

  1. type Customer struct {
  2. Code string `xml:"code"`
  3. Name string `xml:"name"`
  4. }
  5. type Customers struct {
  6. Customers []Customer `xml:"name"`
  7. }

您可以在这里的playground上尝试。问题是您没有为[]Customer分配xml标签。

您解决这个问题的方式,使用xml.Name也是正确的,但更冗长。您可以在这里查看工作代码。如果您出于某种原因需要使用xml.Name字段,我建议使用私有字段,以免导出版本的结构变得混乱。

英文:

The correct structure is the following:

  1. type Customer struct {
  2. Code string `xml:"code"`
  3. Name string `xml:"name"`
  4. }
  5. type Customers struct {
  6. Customers []Customer `xml:"name"`
  7. }

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.

huangapple
  • 本文由 发表于 2013年4月18日 02:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/16067966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定