forked from kokardy/saxlike
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
77 lines (69 loc) · 1.53 KB
/
Copy pathparser.go
File metadata and controls
77 lines (69 loc) · 1.53 KB
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
package saxlike
import (
"encoding/xml"
"io"
)
//SAX-like XML Parser
type Parser struct {
*xml.Decoder
handler Handler
}
//Create a New Parser
func NewParser(reader io.Reader, handler Handler) *Parser {
decoder := xml.NewDecoder(reader)
return &Parser{decoder, handler}
}
//SetHTMLMode make Parser can parse invalid HTML
func (p *Parser) SetHTMLMode() {
p.Strict = false
p.AutoClose = xml.HTMLAutoClose
p.Entity = xml.HTMLEntity
}
//Parse calls handler's methods
//when the parser encount a start-element,a end-element, a comment and so on.
func (p *Parser) Parse() (err error) {
p.handler.StartDocument()
for {
token, err := p.Token()
if err == io.EOF {
err = nil
break
}
if err != nil {
panic(err)
}
switch token.(type) {
case xml.StartElement:
s := token.(xml.StartElement)
p.handler.StartElement(s)
case xml.EndElement:
e := token.(xml.EndElement)
p.handler.EndElement(e)
case xml.CharData:
c := token.(xml.CharData)
p.handler.CharData(c)
case xml.Comment:
com := token.(xml.Comment)
p.handler.Comment(com)
case xml.ProcInst:
pro := token.(xml.ProcInst)
p.handler.ProcInst(pro)
case xml.Directive:
dir := token.(xml.Directive)
p.handler.Directive(dir)
default:
panic("unknown xml token.")
}
}
p.handler.EndDocument()
return
}
//Create a parser and parse
func Parse(reader io.Reader, handler Handler, htmlMode bool) error {
decoder := xml.NewDecoder(reader)
parser := &Parser{decoder, handler}
if htmlMode {
parser.SetHTMLMode()
}
return parser.Parse()
}