-
Notifications
You must be signed in to change notification settings - Fork 8
/
xml.go
110 lines (98 loc) · 1.91 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
package xj2go
import (
"encoding/xml"
"errors"
"io"
"log"
"os"
"strings"
"golang.org/x/net/html/charset"
)
type xmlVal struct {
val string
attr bool
}
func xmlToLeafNodes(filename string) ([]leafNode, error) {
m, err := xmlToMap(filename)
if err != nil {
log.Fatal(err)
return nil, err
}
return leafNodes(m)
}
func xmlToMap(filename string) (map[string]interface{}, error) {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
return nil, err
}
m, err := decodeXML(xml.NewDecoder(file), "", nil)
if err != nil {
return nil, err
}
return m, nil
}
func decodeXML(d *xml.Decoder, sk string, attr []xml.Attr) (map[string]interface{}, error) {
if d.CharsetReader == nil {
d.CharsetReader = func(c string, i io.Reader) (io.Reader, error) {
return charset.NewReaderLabel(c, i)
}
}
m := make(map[string]interface{})
ma := make(map[string]interface{})
if sk != "" {
for _, v := range attr {
ma[v.Name.Local] = xmlVal{v.Value, true}
}
}
for {
t, err := d.Token()
if err != nil {
if err != io.EOF {
return nil, errors.New("xml.Decoder.Token() - " + err.Error())
}
return nil, err
}
switch element := t.(type) {
case xml.StartElement:
if sk == "" {
return decodeXML(d, element.Name.Local, element.Attr)
}
mm, err := decodeXML(d, element.Name.Local, element.Attr)
if err != nil {
return nil, err
}
var k string
var v interface{}
for k, v = range mm {
break
}
if vv, ok := ma[k]; ok {
var a []interface{}
switch vv.(type) {
case []interface{}:
a = vv.([]interface{})
default:
a = []interface{}{vv}
}
a = append(a, v)
ma[k] = a
} else {
ma[k] = v
}
case xml.EndElement:
if len(ma) > 0 {
m[sk] = ma
}
return m, nil
case xml.CharData:
tt := strings.Trim(string(element), "\t\r\b\n ")
if tt != "" {
if sk != "" {
m[sk] = tt
}
}
default:
}
}
}