golang XML未正确解组

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

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.

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:

确定