This repository has been archived by the owner on Dec 12, 2018. It is now read-only.
forked from der-antikeks/go-webdav
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathnode.go
123 lines (101 loc) · 1.9 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package webdav
import (
"encoding/xml"
"io"
"strings"
)
type Node struct {
Name xml.Name
Attr []xml.Attr
Children []*Node
Value string
Parent *Node
}
func NodeFromXmlString(xmls string) (*Node, error) {
rd := strings.NewReader(xmls)
return NodeFromXml(rd)
}
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.CharData:
if cur != nil {
cur.Value = string(tok)
}
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"
if len(n.Children) > 0 {
for _, v := range n.Children {
r += v.String() + "\n"
}
} else if len(n.Value) > 0 {
r += n.Value + "\n"
}
r += "<\\" + n.Name.Local + ">"
return r
}