前言
网上找不到5.1的解答参考,所以只能手动写了一个。仅供参考。
补充5.2到5.4
题目
练习 5.1:修改findlinks代码中遍历n.FirstChild链表的部分,将循环调用visit,改成递归调用。
练习 5.2: 编写函数,记录在HTML树中出现的同名元素的次数。
练习 5.3: 编写函数输出所有text结点的内容。注意不要访问
代码
package main
import (
"fmt"
"os"
"io"
"golang.org/x/net/html"
"html/template"
"log"
)
type NodeCount map[string]int
const templ = `
--------------------------------------
| HTML NODES COUNT |
--------------------------------------
| |
{
{- range $key, $value := . }}
| Type: {
{ $key | printf "%-15s" }} Count: {
{ $value | printf "%-4d" }} |
{
{- end }}
| |
--------------------------------------
`
func (nc NodeCount) Fprint(w io.Writer) {
t := template.Must(template.New("escape").Parse(templ))
if err := t.Execute(w, nc); err != nil {
log.Fatal(err)
}
}
func main() {
doc, err := html.Parse(os.Stdin)
if err != nil {
fmt.Fprintf(o