blob: 63e5a82ea8b3641b5dbe7156027088f7d474902e (
plain)
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
|
package json
import (
"bytes"
"fmt"
//"io"
base "src.userspace.com.au/felix/query"
)
// A Node consists of a NodeType and some data (tag name for
// element nodes, content for text) and are part of a tree of Nodes.
type Node struct {
parent, prevSibling, nextSibling, firstChild, lastChild *Node
nodeType base.NodeType
data string
dataType string
level int
}
func (n *Node) Parent() base.Node {
if n.parent == nil {
return nil
}
return n.parent
}
func (n *Node) NextSibling() base.Node {
if n.nextSibling == nil {
return nil
}
return n.nextSibling
}
func (n *Node) FirstChild() base.Node {
if n.firstChild == nil {
return nil
}
return n.firstChild
}
func (n *Node) PrevSibling() base.Node { return n.prevSibling }
func (n *Node) LastChild() base.Node { return n.lastChild }
func (n *Node) Type() base.NodeType { return base.NodeType(n.nodeType) }
func (n *Node) DataType() string { return n.dataType }
func (n *Node) Attr() []base.Attribute { return nil }
// Data gets the value of the node and all its child nodes.
func (n *Node) Data() string {
return n.data
}
// InnerText gets the value of the node and all its child nodes.
func (n *Node) InnerText() string {
var buf bytes.Buffer
if n.nodeType == base.TextNode {
buf.WriteString(n.data)
} else {
for child := n.firstChild; child != nil; child = child.nextSibling {
buf.WriteString(child.InnerText())
}
}
return buf.String()
}
func (n Node) String() string {
return fmt.Sprintf("[%s] %s(%s)", base.NodeNames[n.nodeType], n.dataType, n.data)
}
func (n Node) PrintTree(level int) {
for i := 1; i <= level; i++ {
fmt.Printf(" ")
}
fmt.Println(n)
for c := n.firstChild; c != nil; c = c.nextSibling {
c.PrintTree(level + 1)
}
}
// ChildNodes gets all child nodes of the node.
func (n *Node) ChildNodes() []*Node {
var a []*Node
for nn := n.firstChild; nn != nil; nn = nn.nextSibling {
a = append(a, nn)
}
return a
}
// SelectElement finds the first of child elements with the
// specified name.
func (n *Node) SelectElement(name string) *Node {
for nn := n.firstChild; nn != nil; nn = nn.nextSibling {
if nn.data == name {
return nn
}
}
return nil
}
|