Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple-types decoder in golang

Tags:

xml-parsing

go

I have an XML document. Some fields have custom format. Example:

<document>
  <title>hello world</title>
  <lines>
   line 1
   line 2
   line 3
  </lines>
</document>

I want to import it into structure like:

type Document struct {
    Title  string   `xml:"title"`
    Lines  []string `xml:"lines"`
}

Is there some way how to implement custom decoder, which will split lines string into array of lines (["line 1", "line 2", "line 3"])?

Its possible to make Lines field a string type and make split after xml import, but it doesn't seems to be very elegant solution. Is there any way i can define custom decoder for line spliting and combine it with xml decoder?

like image 814
Ondra Avatar asked Mar 20 '23 22:03

Ondra


1 Answers

You can achieve this by defining a new type that conforms to the xml.Unmarshaler interface. So rather than making Lines a []string, declare a new type with an appropriate UnmarshalXML method. For instance:

type Lines []string

func (l *Lines) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    var content string
    if err := d.DecodeElement(&content, &start); err != nil {
        return err
    }
    *l = strings.Split(content, "\n")
    return nil
}

You can see a full example here: http://play.golang.org/p/3SBu3bOGjR

If you want to support encoding this type too, you can implement the MarshalXML method in a similar fashion (construct the string content you want and pass that to the encoder).

like image 88
James Henstridge Avatar answered Mar 27 '23 10:03

James Henstridge