/
node.go
72 lines (66 loc) · 1.45 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
package htmlx
import (
"strings"
)
func NodeSearch(node *Node, fn func(node *Node) bool) *Node {
if node == nil {
return nil
}
if fn(node) {
return node
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
if n := NodeSearch(child, fn); n != nil {
return n
}
}
return nil
}
func NodeAttrSearch(node *Node, fn func(attr Attribute) bool) string {
if node == nil {
return ""
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
for _, attr := range child.Attr {
if fn(attr) {
return attr.Val
}
}
if n := NodeAttrSearch(child, fn); n != "" {
return n
}
}
return ""
}
func NodeAttrExists(node *Node, fn func(attr Attribute) bool) bool {
if node == nil {
return false
}
for _, attr := range node.Attr {
if fn(attr) {
return true
}
}
return false
}
func NodeChildren(node *Node, childTags ...string) (nodes []*Node) {
childTag := func() string {
if len(childTags) > 0 && childTags[0] != "" {
return childTags[0]
}
return ""
}()
for child := node.FirstChild; child != nil; child = child.NextSibling {
data := strings.TrimSpace(child.Data)
if data != "" && (childTag == "" || data == childTag) {
nodes = append(nodes, child)
}
}
return
}
func NodeTitle(node *Node) string {
title := NodeSearch(node, func(node *Node) bool {
return node.Type == ElementNode && strings.TrimSpace(node.Data) == "title"
})
return strings.TrimSpace(title.FirstChild.Data)
}