-
Notifications
You must be signed in to change notification settings - Fork 0
/
html-parser.go
192 lines (172 loc) · 4.23 KB
/
html-parser.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
// Importing required packages
import (
"fmt"
"strings"
"unicode"
)
// NodeType defines the type of an HTML node.
type NodeType int
const (
ElementNode NodeType = iota
TextNode
)
// Node represents an HTML node, which can be an element or text.
type Node struct {
Type NodeType
Tag string
Attributes map[string]string
Children []*Node
Content string
}
// Parser holds the HTML data and the position of the current character.
type Parser struct {
html string
pos int
}
// NewParser creates a new Parser instance.
func NewParser(html string) *Parser {
return &Parser{html: html, pos: 0}
}
// Parse parses the HTML and returns the root node.
func (p *Parser) Parse() (*Node, error) {
return p.parseNodes()
}
// parseNodes parses a list of nodes.
func (p *Parser) parseNodes() (*Node, error) {
var root Node
root.Type = ElementNode
root.Tag = "root"
for p.pos < len(p.html) {
p.skipWhitespace()
if p.pos < len(p.html) && p.html[p.pos] == '<' {
if p.html[p.pos+1] == '/' {
p.pos += 2 // skip '</'
p.parseTagName() // read until '>'
p.pos++ // skip '>'
break
} else {
child, err := p.parseElement()
if err != nil {
return nil, err
}
root.Children = append(root.Children, child)
}
} else {
textNode := p.parseText()
if textNode != nil {
root.Children = append(root.Children, textNode)
}
}
}
return &root, nil
}
// parseElement parses an HTML element.
func (p *Parser) parseElement() (*Node, error) {
p.pos++ // skip '<'
tag := p.parseTagName()
attributes := p.parseAttributes()
node := &Node{
Type: ElementNode,
Tag: tag,
Attributes: attributes,
}
if p.pos < len(p.html) && p.html[p.pos] == '>' {
p.pos++ // skip '>'
// Parse children nodes
childNodes, err := p.parseNodes()
if err != nil {
return nil, err
}
node.Children = append(node.Children, childNodes.Children...)
}
return node, nil
}
// parseTagName reads the tag name from the HTML string.
func (p *Parser) parseTagName() string {
start := p.pos
for p.pos < len(p.html) && (unicode.IsLetter(rune(p.html[p.pos])) || unicode.IsDigit(rune(p.html[p.pos]))) {
p.pos++
}
return p.html[start:p.pos]
}
// parseAttributes reads attributes of an HTML tag.
func (p *Parser) parseAttributes() map[string]string {
attributes := make(map[string]string)
for p.pos < len(p.html) && p.html[p.pos] != '>' {
p.skipWhitespace()
name := p.parseTagName()
var value string
if p.pos < len(p.html) && p.html[p.pos] == '=' {
p.pos++ // skip '='
value = p.parseAttributeValue()
}
attributes[name] = value
}
return attributes
}
// parseAttributeValue reads the attribute value enclosed in quotes.
func (p *Parser) parseAttributeValue() string {
if p.pos >= len(p.html) || p.html[p.pos] != '"' {
return ""
}
p.pos++ // skip opening quote
start := p.pos
for p.pos < len(p.html) && p.html[p.pos] != '"' {
p.pos++
}
value := p.html[start:p.pos]
p.pos++ // skip closing quote
return value
}
// parseText parses a text node.
func (p *Parser) parseText() *Node {
start := p.pos
for p.pos < len(p.html) && p.html[p.pos] != '<' {
p.pos++
}
content := strings.TrimSpace(p.html[start:p.pos])
if content == "" {
return nil
}
return &Node{Type: TextNode, Content: content}
}
// skipWhitespace skips whitespace characters.
func (p *Parser) skipWhitespace() {
for p.pos < len(p.html) && unicode.IsSpace(rune(p.html[p.pos])) {
p.pos++
}
}
// printNode recursively prints the HTML structure.
func printNode(node *Node, indent int) {
indentation := strings.Repeat(" ", indent)
if node.Type == ElementNode {
fmt.Printf("%s<%s", indentation, node.Tag)
for attr, val := range node.Attributes {
fmt.Printf(" %s=\"%s\"", attr, val)
}
fmt.Println(">")
for _, child := range node.Children {
printNode(child, indent+1)
}
fmt.Printf("%s</%s>\n", indentation, node.Tag)
} else if node.Type == TextNode {
fmt.Printf("%s%s\n", indentation, node.Content)
}
}
func main() {
html := `<html>
<head><title>=HTML Parser</title></head>
<body>
<h1>Welcome to the Sample Page</h1>
<p>This is a HTML parser.</p>
</body>
</html>`
parser := NewParser(html)
root, err := parser.Parse()
if err != nil {
fmt.Println("Error:", err)
return
}
printNode(root, 0)
}