From d34b820adf64514b5992dbbe5e22007af3ae53dd Mon Sep 17 00:00:00 2001 From: Shulhan Date: Sun, 5 Apr 2020 21:35:08 +0700 Subject: html: add function to simplify iterating node in HTML tree The NodeIterator have the method Next() that will return the first child or the next sibling of current node, iteratively from top to bottom. --- lib/net/html/example_node_iterator_test.go | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 lib/net/html/example_node_iterator_test.go (limited to 'lib/net/html/example_node_iterator_test.go') diff --git a/lib/net/html/example_node_iterator_test.go b/lib/net/html/example_node_iterator_test.go new file mode 100644 index 00000000..b5e82db4 --- /dev/null +++ b/lib/net/html/example_node_iterator_test.go @@ -0,0 +1,94 @@ +// Copyright 2020, Shulhan . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "fmt" + "log" + "strings" +) + +func ExampleParse() { + rawHTML := ` + +` + + r := strings.NewReader(rawHTML) + + iter, err := Parse(r) + if err != nil { + log.Fatal(err) + } + + for node := iter.Next(); node != nil; node = iter.Next() { + if node.IsElement() { + fmt.Printf("%s\n", node.Data) + } else { + fmt.Printf("\t%s\n", node.Data) + } + } + //Output: + //html + //head + //body + //ul + //li + //b + // item + //b + //span + // one + //span + //li + //ul + //body + //html +} + +func ExampleNodeIterator_Set() { + rawHTML := ` + +

Jump here

+` + + r := strings.NewReader(rawHTML) + + iter, err := Parse(r) + if err != nil { + log.Fatal(err) + } + + for node := iter.Next(); node != nil; node = iter.Next() { + if node.IsElement() { + if node.Data == "ul" { + // Skip iterating the "ul" element. + iter.SetNext(node.GetNextSibling()) + continue + } + fmt.Printf("%s\n", node.Data) + } else { + fmt.Printf("\t%s\n", node.Data) + } + } + //Output: + //html + //head + //body + //h2 + // Jump here + //h2 + //body + //html +} -- cgit v1.3-5-g9baa