-
Notifications
You must be signed in to change notification settings - Fork 43
/
parse.go
82 lines (73 loc) · 2.05 KB
/
parse.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
73
74
75
76
77
78
79
80
81
82
package gowd
import (
"errors"
"fmt"
"io"
"io/ioutil"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
//ElementsMap maps Elements by their `id` attributes
type ElementsMap map[string]*Element
//NewElementMap creates a new ElementMap
func NewElementMap() ElementsMap {
return make(ElementsMap)
}
//ParseElements parse an html fragment and return a list of elements
func ParseElements(r io.Reader, em ElementsMap) ([]*Element, error) {
nodes, err := html.ParseFragment(r, &html.Node{
Type: html.ElementNode,
Data: "body",
DataAtom: atom.Body,
})
if err != nil {
return nil, err
}
elems := make([]*Element, 0)
for _, node := range nodes {
elems = append(elems, NewElementFromNode(node, em))
}
return elems, nil
}
//NewElementFromNode creates an element from existing node
func NewElementFromNode(node *html.Node, em ElementsMap) *Element {
elem := &Element{
data: elementText(node.Data),
Attributes: node.Attr,
nodeType: node.Type,
Kids: make([]*Element, 0),
eventHandlers: make(map[string]EventHandler),
}
if em != nil && elem.GetID() != "" {
em[elem.GetID()] = elem
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
elem.AddElement(NewElementFromNode(c, em))
}
return elem
}
//ParseElement parses an html with only one root tag, returns the root element.
func ParseElement(innerHTML string, em ElementsMap) (*Element, error) {
elems, err := ParseElements(strings.NewReader(innerHTML), em)
if err != nil {
return nil, err
}
if len(elems) != 1 {
tags := "["
for _, e := range elems {
tags += fmt.Sprintf("%v:'%s', ", e.nodeType, strings.Trim(e.data, "\t\n\r "))
}
tags += "]"
return nil, errors.New("The provided html must yield only one html element, I have: " + tags)
}
return elems[0], nil
}
//ParseElementFromFile like ParseElement, but reads input from a file
func ParseElementFromFile(fileName string, em ElementsMap) (*Element, error) {
data, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
return ParseElement(string(data), em)
}