Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang XML not unmarshal-ing properly

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} []}

like image 228
Darrrrrren Avatar asked Apr 17 '13 18:04

Darrrrrren


1 Answers

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.

like image 165
nemo Avatar answered Oct 19 '22 15:10

nemo