forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (67 loc) · 1.27 KB
/
main.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
// ex5.17 uses a variadic ElementsByTagName function to find html nodes.
package main
import (
"fmt"
"log"
"os"
"golang.org/x/net/html"
)
func ElementsByTag(n *html.Node, tags ...string) []*html.Node {
nodes := make([]*html.Node, 0)
keep := make(map[string]bool, len(tags))
for _, t := range tags {
keep[t] = true
}
pre := func(n *html.Node) bool {
if n.Type != html.ElementNode {
return true
}
_, ok := keep[n.Data]
if ok {
nodes = append(nodes, n)
}
return true
}
forEachElement(n, pre, nil)
return nodes
}
func forEachElement(n *html.Node, pre, post func(n *html.Node) bool) *html.Node {
u := make([]*html.Node, 0) // unvisited
u = append(u, n)
for len(u) > 0 {
n = u[0]
u = u[1:]
if pre != nil {
if !pre(n) {
return n
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
u = append(u, c)
}
if post != nil {
if !post(n) {
return n
}
}
}
return nil
}
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "usage: ex5.17 HTML_FILE TAG ...")
}
filename := os.Args[1]
tags := os.Args[2:]
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
doc, err := html.Parse(file)
if err != nil {
log.Fatal(err)
}
for _, n := range ElementsByTag(doc, tags...) {
fmt.Printf("%+v\n", n)
}
}