]> Cypherpunks repositories - gostls13.git/commitdiff
exp/html: update package docs and add an example; a node's children is
authorNigel Tao <nigeltao@golang.org>
Wed, 17 Oct 2012 23:25:50 +0000 (10:25 +1100)
committerNigel Tao <nigeltao@golang.org>
Wed, 17 Oct 2012 23:25:50 +0000 (10:25 +1100)
a linked list, not a slice.

R=r, minux.ma
CC=golang-dev
https://golang.org/cl/6618055

src/pkg/exp/html/doc.go
src/pkg/exp/html/example_test.go [new file with mode: 0644]

index 56b194ffb9080c3ec6d77784a47403e9ddb7ce5c..4dd453091c63a92555ffcab0f5f625c61e586f7b 100644 (file)
@@ -84,7 +84,7 @@ example, to process each anchor node in depth-first order:
                if n.Type == html.ElementNode && n.Data == "a" {
                        // Do something with n...
                }
-               for _, c := range n.Child {
+               for c := n.FirstChild; c != nil; c = c.NextSibling {
                        f(c)
                }
        }
diff --git a/src/pkg/exp/html/example_test.go b/src/pkg/exp/html/example_test.go
new file mode 100644 (file)
index 0000000..c15e9a2
--- /dev/null
@@ -0,0 +1,39 @@
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This example demonstrates parsing HTML data and walking the resulting tree.
+package html_test
+
+import (
+       "exp/html"
+       "fmt"
+       "log"
+       "strings"
+)
+
+func ExampleParse() {
+       s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
+       doc, err := html.Parse(strings.NewReader(s))
+       if err != nil {
+               log.Fatal(err)
+       }
+       var f func(*html.Node)
+       f = func(n *html.Node) {
+               if n.Type == html.ElementNode && n.Data == "a" {
+                       for _, a := range n.Attr {
+                               if a.Key == "href" {
+                                       fmt.Println(a.Val)
+                                       break
+                               }
+                       }
+               }
+               for c := n.FirstChild; c != nil; c = c.NextSibling {
+                       f(c)
+               }
+       }
+       f(doc)
+       // Output:
+       // foo
+       // /bar/baz
+}