forked from basgys/goxml2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
47 lines (40 loc) · 978 Bytes
/
struct.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
package xml2json
import (
"strings"
)
// Node is a data element on a tree
type Node struct {
Children map[string]Nodes
Data string
ChildrenAlwaysAsArray bool
}
// Nodes is a list of nodes
type Nodes []*Node
// AddChild appends a node to the list of children
func (n *Node) AddChild(s string, c *Node) {
// Lazy lazy
if n.Children == nil {
n.Children = map[string]Nodes{}
}
n.Children[s] = append(n.Children[s], c)
}
// IsComplex returns whether it is a complex type (has children)
func (n *Node) IsComplex() bool {
return len(n.Children) > 0
}
// GetChild returns child by path if exists. Path looks like "grandparent.parent.child.grandchild"
func (n *Node) GetChild(path string) *Node {
result := n
names := strings.Split(path, ".")
for _, name := range names {
children, exists := result.Children[name]
if !exists {
return nil
}
if len(children) == 0 {
return nil
}
result = children[0]
}
return result
}