forked from oec/goparsify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
56 lines (45 loc) · 1.19 KB
/
html.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
package html
import (
. "github.com/db48x/goparsify"
)
func parse(input string) (result interface{}, err error) {
return Run(tag, input)
}
type htmlTag struct {
Name string
Attributes map[string]string
Body []interface{}
}
var (
tag Parser
identifier = Regex("[a-zA-Z][a-zA-Z0-9]*")
text = NotChars("<>").Map(func(n *Result) { n.Result = n.Token })
element = Any(text, &tag)
elements = Some(element).Map(func(n *Result) {
ret := []interface{}{}
for _, child := range n.Child {
ret = append(ret, child.Result)
}
n.Result = ret
})
attr = Seq(identifier, "=", StringLit(`"'`))
attrs = Some(attr).Map(func(node *Result) {
attr := map[string]string{}
for _, attrNode := range node.Child {
attr[attrNode.Child[0].Token] = attrNode.Child[2].Token
}
node.Result = attr
})
tstart = Seq("<", identifier, Cut(), attrs, ">")
tend = Seq("</", Cut(), identifier, ">")
)
func init() {
tag = Seq(tstart, Cut(), elements, tend).Map(func(node *Result) {
openTag := node.Child[0]
node.Result = htmlTag{
Name: openTag.Child[1].Token,
Attributes: openTag.Child[3].Result.(map[string]string),
Body: node.Child[2].Result.([]interface{}),
}
})
}