-
Notifications
You must be signed in to change notification settings - Fork 23
/
node.go
108 lines (87 loc) · 1.61 KB
/
node.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 webdav
import (
"encoding/xml"
"io"
)
type Node struct {
Name xml.Name
Attr []xml.Attr
Children []*Node
Parent *Node
}
func NodeFromXml(r io.Reader) (*Node, error) {
var cur, parent *Node
decoder := xml.NewDecoder(r)
for {
token, err := decoder.Token()
if err != nil {
if err != io.EOF {
return nil, err
}
break
}
switch tok := token.(type) {
case xml.StartElement:
parent = cur
// if tok.Name.Space != "DAV:" {
if tok.Name.Space == "" {
return nil, ErrMalformedXml
}
cur = &Node{
Name: tok.Name,
Attr: tok.Attr,
Parent: parent,
}
if parent != nil {
parent.Children = append(parent.Children, cur)
}
case xml.EndElement:
if cur.Parent == nil {
return cur, nil
}
cur = cur.Parent
default:
//log.Printf("%T", tok)
}
}
return cur, nil
}
func (n Node) HasChildren(name string) bool {
for _, v := range n.Children {
if v.Name.Local == name {
return true
}
}
return false
}
func (n *Node) GetChildrens(name string) []*Node {
if name == "*" {
return n.Children
}
var ret []*Node
for _, v := range n.Children {
if v.Name.Local == name {
ret = append(ret, v)
}
}
return ret
}
func (n *Node) FirstChildren(name string) *Node {
if name == "*" && len(n.Children) > 0 {
return n.Children[0]
}
for _, v := range n.Children {
if v.Name.Local == name {
return v
}
}
return nil
}
func (n *Node) String() string {
r := "<" + n.Name.Local + " xmlns=\"" + n.Name.Space + "\">\n"
for _, v := range n.Children {
r += v.String() + "\n"
}
r += "<\\" + n.Name.Local + ">"
return r
}