~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/golang.org/x/net/html/example_test.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2012 The Go Authors. All rights reserved.
 
2
// Use of this source code is governed by a BSD-style
 
3
// license that can be found in the LICENSE file.
 
4
 
 
5
// This example demonstrates parsing HTML data and walking the resulting tree.
 
6
package html_test
 
7
 
 
8
import (
 
9
        "fmt"
 
10
        "log"
 
11
        "strings"
 
12
 
 
13
        "golang.org/x/net/html"
 
14
)
 
15
 
 
16
func ExampleParse() {
 
17
        s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
 
18
        doc, err := html.Parse(strings.NewReader(s))
 
19
        if err != nil {
 
20
                log.Fatal(err)
 
21
        }
 
22
        var f func(*html.Node)
 
23
        f = func(n *html.Node) {
 
24
                if n.Type == html.ElementNode && n.Data == "a" {
 
25
                        for _, a := range n.Attr {
 
26
                                if a.Key == "href" {
 
27
                                        fmt.Println(a.Val)
 
28
                                        break
 
29
                                }
 
30
                        }
 
31
                }
 
32
                for c := n.FirstChild; c != nil; c = c.NextSibling {
 
33
                        f(c)
 
34
                }
 
35
        }
 
36
        f(doc)
 
37
        // Output:
 
38
        // foo
 
39
        // /bar/baz
 
40
}