42 lines
888 B
Go
42 lines
888 B
Go
package main
|
||
|
||
import (
|
||
"Study/src/study/day7Function/HtmlTools"
|
||
"fmt"
|
||
"golang.org/x/net/html"
|
||
)
|
||
|
||
// forEachNode 针对每个结点x,都会调用pre(x)和post(x)。
|
||
// pre和post都是可选的。
|
||
// 遍历孩子结点之前,pre被调用
|
||
// 遍历孩子结点之后,post被调用
|
||
func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
|
||
if pre != nil {
|
||
pre(n)
|
||
}
|
||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||
forEachNode(c, pre, post)
|
||
}
|
||
if post != nil {
|
||
post(n)
|
||
}
|
||
}
|
||
|
||
func main() {
|
||
var depth int
|
||
|
||
var startElement func(n *html.Node) = func(n *html.Node) {
|
||
if n.Type == html.ElementNode {
|
||
fmt.Printf("%*s<%s>\n", depth*2, "", n.Data)
|
||
depth++
|
||
}
|
||
}
|
||
endElement := func(n *html.Node) {
|
||
if n.Type == html.ElementNode {
|
||
depth--
|
||
fmt.Printf("%*s</%s>\n", depth*2, "", n.Data)
|
||
}
|
||
}
|
||
forEachNode(HtmlTools.GetHtml(), startElement, endElement)
|
||
}
|