Kroid
Kroid

Reputation: 1100

Golang XML parse

My XML data:

<dictionary version="0.8" revision="403605">
    <grammemes>
        <grammeme parent="">POST</grammeme>
        <grammeme parent="POST">NOUN</grammeme>
    </grammemes>
</dictionary>

My code:

type Dictionary struct {
    XMLName xml.Name `xml:"dictionary"`
    Grammemes *Grammemes `xml:"grammemes"`
}

type Grammemes struct {
    Grammemes []*Grammeme `xml:"grammeme"`
}

type Grammeme struct {
    Name string `xml:"grammeme"`
    Parent string `xml:"parent,attr"`
}

I get Grammeme.Parent attribute, but i don't get Grammeme.Name. Why?

Upvotes: 8

Views: 12210

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

If you want a field to hold the contents of the current element, you can use the tag xml:",chardata". The way you've tagged your structure, it is instead looking for a <grammeme> sub-element.

So one set of structures you could decode into is:

type Dictionary struct {
    XMLName   xml.Name   `xml:"dictionary"`
    Grammemes []Grammeme `xml:"grammemes>grammeme"`
}

type Grammeme struct {
    Name   string `xml:",chardata"`
    Parent string `xml:"parent,attr"`
}

You can test out this example here: http://play.golang.org/p/7lQnQOCh0I

Upvotes: 12

Related Questions