forked from lucsky/go-exml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exml.go
108 lines (94 loc) · 2.03 KB
/
exml.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package exml
import (
"bytes"
"encoding/xml"
"errors"
"io"
"strings"
)
type Handler interface{}
type ElemHandler func(Attrs)
type TextHandler func(CharData)
type ErrorHandler func(error)
type Decoder struct {
decoder *xml.Decoder
handlers map[string]Handler
errorHandler ErrorHandler
events []string
text *bytes.Buffer
}
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
decoder: xml.NewDecoder(r),
handlers: make(map[string]Handler),
events: []string{"/"},
text: new(bytes.Buffer),
}
}
func (d *Decoder) On(event string, handler Handler) {
fullEvent := strings.Join(append(d.events, event), "/")
d.handlers[fullEvent] = handler
}
func (d *Decoder) OnError(handler ErrorHandler) {
d.errorHandler = handler
}
func (d *Decoder) Run() {
for {
token, err := d.decoder.Token()
if token == nil {
if d.errorHandler != nil {
d.errorHandler(err)
}
break
}
switch t := token.(type) {
case xml.StartElement:
d.text.Reset()
d.events = append(d.events, t.Name.Local)
handler := d.getHandler()
if handler != nil {
handler.(func(Attrs))(t.Attr)
}
break
case xml.CharData:
d.text.Write(t)
break
case xml.EndElement:
numPop := 1
if d.text.Len() > 0 {
numPop = 2
d.events = append(d.events, "$text")
handler := d.getHandler()
if handler != nil {
handler.(func(CharData))(d.text.Bytes())
}
}
d.events = d.events[:len(d.events)-numPop]
break
}
}
}
func (d *Decoder) Assign(slot *string) func(CharData) {
return func(c CharData) {
*slot = string(c)
}
}
func (d *Decoder) Append(a *[]string) func(CharData) {
return func(c CharData) {
*a = append(*a, string(c))
}
}
func (d *Decoder) getHandler() Handler {
fullEvent := strings.Join(d.events, "/")
return d.handlers[fullEvent]
}
type Attrs []xml.Attr
type CharData xml.CharData
func (a Attrs) Get(name string) (string, error) {
for _, attr := range a {
if attr.Name.Local == name {
return attr.Value, nil
}
}
return "", errors.New("attribute not found")
}