Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang XML parse

Tags:

xml

go

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?

like image 357
Kroid Avatar asked Mar 26 '14 08:03

Kroid


1 Answers

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

like image 135
James Henstridge Avatar answered Oct 28 '22 00:10

James Henstridge