-
Notifications
You must be signed in to change notification settings - Fork 1
/
xml.go
143 lines (117 loc) · 2.78 KB
/
xml.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package reactor
import (
"encoding/xml"
"fmt"
"io"
"strconv"
"strings"
)
func MustParseDisplayModel(src string) *DisplayModel {
ret, err := ParseDisplayModel(src)
if err != nil {
panic(err)
}
return ret
}
func ParseDisplayModel(src string) (*DisplayModel, error) {
src = strings.TrimSpace(src)
reader := strings.NewReader(src)
decoder := xml.NewDecoder(reader)
stack := []*DisplayModel{}
for {
token, err := decoder.Token()
// fmt.Println("token", token)
if token == nil && err == io.EOF {
var result *DisplayModel
if len(stack) > 0 {
result = stack[0]
}
return result, nil
}
if err != nil {
return nil, err
}
switch t := token.(type) {
case xml.StartElement:
model := &DisplayModel{
Element: t.Name.Local,
Attributes: map[string]interface{}{},
}
for _, attribute := range t.Attr {
if attribute.Name.Local == "id" {
model.ID = attribute.Value
} else if attribute.Name.Local == "reportEvents" {
re := []ReportEvent{}
evts := strings.Split(attribute.Value, " ")
for _, evtString := range evts {
parts := strings.Split(evtString, ":")
rest := parts[1:]
sp := false
pd := false
extraValues := []string{}
for _, v := range rest {
switch v {
case "SP":
sp = true
case "PD":
pd = true
default:
if strings.HasPrefix(v, "X-") {
extraValues = append(extraValues, v[2:])
} else {
return nil, fmt.Errorf("Unknown reportEvent parameter %#v", v)
}
}
}
evt := ReportEvent{
Name: parts[0],
StopPropagation: sp,
PreventDefault: pd,
ExtraValues: extraValues,
}
re = append(re, evt)
}
model.ReportEvents = re
} else {
var value interface{} = attribute.Value
if attribute.Name.Space == "bool" {
value, err = strconv.ParseBool(attribute.Value)
if err != nil {
return nil, err
}
} else if attribute.Name.Space == "int" {
value, err = strconv.Atoi(attribute.Value)
if err != nil {
return nil, err
}
}
if attribute.Name.Local == "htmlID" {
model.Attributes["id"] = value
} else {
model.Attributes[attribute.Name.Local] = value
}
}
}
if len(stack) != 0 {
prev := stack[len(stack)-1]
prev.Children = append(prev.Children, model)
}
stack = append(stack, model)
case xml.CharData:
if len(stack) != 0 {
text := string(t)
prev := stack[len(stack)-1]
if text != "" && strings.TrimSpace(text) != "" {
model := &DisplayModel{
Text: text,
}
prev.Children = append(prev.Children, model)
}
}
case xml.EndElement:
if len(stack) > 1 {
stack = stack[:len(stack)-1]
}
}
}
}