forked from clbanning/x2j
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader2j.go
105 lines (85 loc) · 2.09 KB
/
reader2j.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
// io.Reader --> map[string]interface{} or JSON string
// nothing magic - just implements generic Go case
package x2j
import (
"encoding/json"
"encoding/xml"
"io"
)
// ToTree() - parse a XML io.Reader to a tree of Nodes
func ToTree(rdr io.Reader) (*Node, error) {
p := xml.NewDecoder(rdr)
p.CharsetReader = X2jCharsetReader
n, perr := xmlToTree("", nil, p)
if perr != nil {
return nil, perr
}
return n, nil
}
// ToMap() - parse a XML io.Reader to a map[string]interface{}
func ToMap(rdr io.Reader, recast ...bool) (map[string]interface{}, error) {
var r bool
if len(recast) == 1 {
r = recast[0]
}
n, err := ToTree(rdr)
if err != nil {
return nil, err
}
m := make(map[string]interface{})
m[n.key] = n.treeToMap(r)
return m, nil
}
// ToJson() - parse a XML io.Reader to a JSON string
func ToJson(rdr io.Reader, recast ...bool) (string, error) {
var r bool
if len(recast) == 1 {
r = recast[0]
}
m, merr := ToMap(rdr, r)
if m == nil || merr != nil {
return "", merr
}
b, berr := json.Marshal(m)
if berr != nil {
return "", berr
}
return string(b), nil
}
// ToJsonIndent - the pretty form of ReaderToJson
func ToJsonIndent(rdr io.Reader, recast ...bool) (string, error) {
var r bool
if len(recast) == 1 {
r = recast[0]
}
m, merr := ToMap(rdr, r)
if m == nil || merr != nil {
return "", merr
}
b, berr := json.MarshalIndent(m, "", " ")
if berr != nil {
return "", berr
}
// NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML.
return string(b), nil
}
// ReaderValuesFromTagPath - io.Reader version of ValuesFromTagPath()
func ReaderValuesFromTagPath(rdr io.Reader, path string, getAttrs ...bool) ([]interface{}, error) {
var a bool
if len(getAttrs) == 1 {
a = getAttrs[0]
}
m, err := ToMap(rdr)
if err != nil {
return nil, err
}
return ValuesFromKeyPath(m, path, a), nil
}
// ReaderValuesForTag - io.Reader version of ValuesForTag()
func ReaderValuesForTag(rdr io.Reader, tag string) ([]interface{}, error) {
m, err := ToMap(rdr)
if err != nil {
return nil, err
}
return ValuesForKey(m, tag), nil
}