package main
import (
"bytes"
"fmt"
"os"
"strings"
"golang.org/x/net/html"
)
var raw = `
First node first child
Second node second child
`
func main() {
doc, err := html.Parse(bytes.NewReader([]byte(raw)))
if err != nil {
fmt.Fprintf(os.Stderr, "Parsing failed: %s\n", err)
os.Exit(-1)
}
words, images := counterofwordsandimages(doc)
fmt.Printf("There are %d words and %d images\n", words, images)
}
func counterofwordsandimages(doc *html.Node) (int, int) {
var words, images int
visit(doc, &words, &images)
return words, images
}
func visit(n *html.Node, words, images *int) {
if n.Type == html.TextNode {
*words += len(strings.Fields(n.Data))
} else if n.Type == html.ElementNode && n.Data == "img" {
*images++
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
visit(c, words, images)
}
}