-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.go
53 lines (41 loc) · 954 Bytes
/
map.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package icache
import (
"encoding/xml"
"fmt"
)
type mapContainer struct {
Content []mapElement `xml:",any"`
}
type mapElement struct {
XMLName xml.Name
Content string `xml:",chardata"`
}
type Map map[string]string
func (m Map) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
c := mapContainer{
Content: make([]mapElement, 0, len(m)),
}
for k, v := range m {
c.Content = append(c.Content, mapElement{
XMLName: xml.Name{Local: k},
Content: v,
})
}
e.EncodeElement(c, start)
return nil
}
func (m *Map) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var c mapContainer
if err := d.DecodeElement(&c, &start); err != nil {
return err
}
res := make(map[string]string, len(c.Content))
for _, el := range c.Content {
if _, ok := res[el.XMLName.Local]; ok {
return fmt.Errorf("field already defined - %s", el.XMLName.Local)
}
res[el.XMLName.Local] = el.Content
}
*m = res
return nil
}