Parsing XML with Go having multiple lowercase elements

I don't know how to get this code to work. I'm just trying to parse a simple XML file like this:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName xml.Name `xml:"data"`
    Nam     string   `xml:"nam,attr"`
}

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data
}

func main() {

    x := `  
        <struct>
            <data nam="MESSAGE_TYPE">     
            </data>
            <data nam="MESSAGE_TYPE2">
            </data>
        </struct>
    `
    s := Struct{}
    err := xml.Unmarshal([]byte(x), &s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", s)
    fmt.Println(s.Data)
}

      

what i got:

{{ struct} []}
[]

      

But when I change items to uppercase like:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName xml.Name `xml:"data"`
    Nam     string   `xml:"nam,attr"`
}

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data
}

func main() {

    x := `  
        <struct>
            <data nam="MESSAGE_TYPE">     
            </data>
            <data nam="MESSAGE_TYPE2">
            </data>
        </struct>
    `
    s := Struct{}
    err := xml.Unmarshal([]byte(x), &s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", s)
    fmt.Println(s.Data)
}

      

I got it:

{{ struct} [{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]}
[{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]

      

Can anyone tell me why?

+3


source to share


1 answer


If you do not put an XML annotation in a structure field, the field name is taken as the XML element name.

In the Unmarshal documentation in the endoding / xml package we can find the following:

Unmarshal maps an XML element to a structure using the following rules. In rules, the field tag refers to the value associated with the "xml" key in the structure field tag (see example above).

  • If the XML element contains a subelement whose name matches a field without mode flags (", attr", ", chardata", etc.), Unmarshal matches the subelement to that structure field.


Matching is case sensitive, so it matters in your case.

I recommend annotating a structure like this to fit the actual data:

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data   `xml:"data"`
}

      

+6


source







All Articles