forked from lestrrat-go/libxml2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libxml2_example_test.go
72 lines (59 loc) · 1.51 KB
/
libxml2_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package libxml2_test
import (
"log"
"net/http"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/parser"
"github.com/lestrrat-go/libxml2/types"
"github.com/lestrrat-go/libxml2/xpath"
)
func ExampleXML() {
res, err := http.Get("http://blog.golang.org/feed.atom")
if err != nil {
panic("failed to get blog.golang.org: " + err.Error())
}
p := parser.New()
doc, err := p.ParseReader(res.Body)
defer res.Body.Close()
if err != nil {
panic("failed to parse XML: " + err.Error())
}
defer doc.Free()
doc.Walk(func(n types.Node) error {
log.Printf(n.NodeName())
return nil
})
root, err := doc.DocumentElement()
if err != nil {
log.Printf("Failed to fetch document element: %s", err)
return
}
ctx, err := xpath.NewContext(root)
if err != nil {
log.Printf("Failed to create xpath context: %s", err)
return
}
defer ctx.Free()
ctx.RegisterNS("atom", "http://www.w3.org/2005/Atom")
title := xpath.String(ctx.Find("/atom:feed/atom:title/text()"))
log.Printf("feed title = %s", title)
}
func ExampleHTML() {
res, err := http.Get("http://golang.org")
if err != nil {
panic("failed to get golang.org: " + err.Error())
}
doc, err := libxml2.ParseHTMLReader(res.Body)
if err != nil {
panic("failed to parse HTML: " + err.Error())
}
defer doc.Free()
doc.Walk(func(n types.Node) error {
log.Printf(n.NodeName())
return nil
})
nodes := xpath.NodeList(doc.Find(`//div[@id="menu"]/a`))
for i := 0; i < len(nodes); i++ {
log.Printf("Found node: %s", nodes[i].NodeName())
}
}