diff options
| author | Shulhan <m.shulhan@gmail.com> | 2020-04-05 21:35:08 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2020-04-05 21:35:08 +0700 |
| commit | d34b820adf64514b5992dbbe5e22007af3ae53dd (patch) | |
| tree | 7222267b6e0473b269e51d852af08e195853bcab /lib/net/html/example_node_iterator_test.go | |
| parent | fe987df87daa808c369b4e2f1c1fa4071e1e80e6 (diff) | |
| download | pakakeh.go-d34b820adf64514b5992dbbe5e22007af3ae53dd.tar.xz | |
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.
Diffstat (limited to 'lib/net/html/example_node_iterator_test.go')
| -rw-r--r-- | lib/net/html/example_node_iterator_test.go | 94 |
1 files changed, 94 insertions, 0 deletions
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 <m.shulhan@gmail.com>. 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 := ` +<ul> + <li> + <b>item</b> + <span>one</span> + </li> +</ul> +` + + 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 := ` +<ul> + <li> + <b>item</b> + <span>one</span> + </li> +</ul> +<h2>Jump here</h2> +` + + 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 +} |
