Golang multiple type decoder

I have an XML document. Some fields have their own format. Example:

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

I want to import it into a structure, for example:

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

Is there a way to implement a custom decoder that splits a string of strings into an array of strings ( ["line 1", "line 2", "line 3"])?

It can be made Lines a string type field and split after xml import, but this does not seem to be a very elegant solution. Is there a way to define a custom decoder for line splitting and combine it with an xml decoder?

+4
source share
2 answers

, , xml.Unmarshaler. Lines a []string UnmarshalXML. :

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
}

: http://play.golang.org/p/3SBu3bOGjR

, MarshalXML ( ).

+7

, CSE:

type Document struct {
    Title    string `xml:"title"`
    LineData string `xml:"lines"`
}

func (d *Document)Lines() []string {
    return strings.Split(d.LineData, '\n')
}

, net/http Request: .

, , , - . , , .

JSON - , .

func (d *Document) Map() map[string]interface{} {
    m := make(map[string]interface{})
    m["lines"] = strings.Split(d.LineData, '\n')
    m["title"] = d.Title
    return m
}
0

All Articles