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.

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失