-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxmlParser.ts
More file actions
262 lines (247 loc) · 8.46 KB
/
xmlParser.ts
File metadata and controls
262 lines (247 loc) · 8.46 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// -------------------------
// XML Model & Parser
// -------------------------
// Text node.
import { XmlText } from './model/xmlText';
import { XmlComment } from './model/xmlComment';
import { XmlProcessing } from './model/xmlProcessing';
import { XmlCData } from './model/xmlCData';
import { XmlDoctype } from './model/xmlDoctype';
import { XmlAttribute } from './model/xmlAttribute';
import { XmlDocument } from './model/xmlDocument';
import { XmlChildNode, XmlElement } from './model/xmlElement';
// A simple recursive-descent XML parser.
// This parser makes explicit checks for termination of constructs and provides detailed error messages.
export class XmlParser {
pos: number = 0;
constructor(public input: string) {}
static parseFragment(xml: string): XmlChildNode[] {
return XmlParser.parse(`<root>${xml}</root>`).getRootElement().children;
}
static parse(xml: string): XmlDocument {
const parser = new XmlParser(xml);
const children: (XmlChildNode | XmlDoctype)[] = [];
while (parser.pos < parser.input.length) {
const node = parser.parseNode();
if (node) {
children.push(node);
} else {
break;
}
}
return new XmlDocument(children);
}
parseNode(): XmlChildNode | XmlDoctype | null {
if (this.peek() === '<') {
if (this.input.startsWith('<!--', this.pos)) {
return this.parseComment();
} else if (this.input.startsWith('<![CDATA[', this.pos)) {
return this.parseCData();
} else if (this.input.startsWith('<!DOCTYPE', this.pos)) {
return this.parseDoctype();
} else if (this.input.startsWith('<?', this.pos)) {
return this.parseProcessing();
} else if (this.input.startsWith('</', this.pos)) {
// End tag encountered; let caller handle.
return null;
} else {
return this.parseElement();
}
} else {
return this.parseText();
}
}
parseText(): XmlText {
const start = this.pos;
while (this.pos < this.input.length && this.peek() !== '<') {
this.pos++;
}
const text = this.input.substring(start, this.pos);
return new XmlText(text);
}
parseComment(): XmlComment {
const start = this.pos;
this.pos += 4; // skip "<!--"
const end = this.input.indexOf('-->', this.pos);
if (end === -1) {
throw new Error(`Unterminated comment starting at position ${start}`);
}
const commentContent = this.input.substring(this.pos, end);
this.pos = end + 3; // skip "-->"
return new XmlComment(commentContent);
}
parseProcessing(): XmlProcessing {
const start = this.pos;
this.pos += 2; // skip "<?"
const target = this.readName();
const wsAfterTarget = this.readWhitespace();
const end = this.input.indexOf('?>', this.pos);
if (end === -1) {
throw new Error(`Unterminated processing instruction starting at position ${start}`);
}
const data = this.input.substring(this.pos, end);
this.pos = end + 2; // skip "?>"
return new XmlProcessing(target, wsAfterTarget, data);
}
parseCData(): XmlCData {
const start = this.pos;
this.pos += 9; // skip "<![CDATA["
const end = this.input.indexOf(']]>', this.pos);
if (end === -1) {
throw new Error(`Unterminated CDATA section starting at position ${start}`);
}
const cdataContent = this.input.substring(this.pos, end);
this.pos = end + 3; // skip "]]>"
return new XmlCData(cdataContent);
}
parseDoctype(): XmlDoctype {
const start = this.pos;
this.pos += 9; // skip "<!DOCTYPE"
const end = this.input.indexOf('>', this.pos);
if (end === -1) {
throw new Error(`Unterminated DOCTYPE declaration starting at position ${start}`);
}
const content = this.input.substring(this.pos, end).trim();
this.pos = end + 1; // skip ">"
return new XmlDoctype(content);
}
parseElement(): XmlElement {
const start = this.pos;
if (this.peek() !== '<') {
throw new Error(`Expected '<' at position ${this.pos}`);
}
this.pos++; // skip "<"
const tagName = this.readName();
if (tagName === '') {
throw new Error(`Expected tag name at position ${this.pos}`);
}
const attributes: XmlAttribute[] = [];
let attrTrailingWs = '';
// Parse attributes until we hit ">" or "/>".
while (this.pos < this.input.length && !this.startsWithAny(['>', '/>'])) {
const leadingWs = this.readWhitespace();
if (this.startsWithAny(['>', '/>'])) {
// The whitespace belongs to the element.
attrTrailingWs = leadingWs;
break;
}
const attrName = this.readName();
if (attrName === '') {
throw new Error(`Expected attribute name at position ${this.pos}`);
}
let wsBeforeEqual = this.readWhitespace();
let wsAfterEqual = '';
let quote = '"';
let value = '';
let hasValue = true;
if (this.peek() === '=') {
this.pos++; // skip "="
wsAfterEqual = this.readWhitespace();
quote = this.peek();
if (quote === '"' || quote === "'") {
this.pos++; // skip opening quote
const startVal = this.pos;
const endVal = this.input.indexOf(quote, this.pos);
if (endVal === -1) {
throw new Error(`Unterminated attribute value for "${attrName}" starting at position ${startVal}`);
}
value = this.input.substring(startVal, endVal);
this.pos = endVal + 1; // skip closing quote
} else {
throw new Error(`Expected quote character at position ${this.pos} for attribute "${attrName}"`);
}
} else {
hasValue = false;
this.pos -= wsBeforeEqual.length; // Rewind to before the whitespace
wsBeforeEqual = '';
}
attributes.push(
new XmlAttribute(
attrName,
value,
leadingWs,
wsBeforeEqual,
wsAfterEqual,
quote === '"' || quote === "'" ? quote : '"',
hasValue,
),
);
}
// End of open tag.
let selfClosing = false;
if (this.startsWithAny(['/>'])) {
selfClosing = true;
this.pos += 2;
} else if (this.peek() === '>') {
this.pos++;
} else {
throw new Error(`Expected '>' or '/>' at position ${this.pos}`);
}
// Parse children if not self-closing.
const children: XmlChildNode[] = [];
let closeTagWs = '';
if (!selfClosing) {
while (this.pos < this.input.length) {
if (this.input.startsWith(`</${tagName}`, this.pos)) {
break;
}
const child = this.parseNode();
if (child instanceof XmlDoctype) {
throw new Error(`Unexpected node type XmlDoctype as child of <${tagName}> at position ${this.pos}`);
}
if (child) {
children.push(child);
} else {
break;
}
}
// Parse closing tag.
if (this.input.startsWith(`</${tagName}`, this.pos)) {
this.pos += 2; // skip "</"
const closingTagName = this.readName();
if (closingTagName !== tagName) {
throw new Error(
`Mismatched closing tag at position ${this.pos}: expected </${tagName}> but found </${closingTagName}>`,
);
}
closeTagWs = this.readWhitespace();
if (this.peek() === '>') {
this.pos++; // skip ">"
} else {
throw new Error(`Expected '>' at end of closing tag for <${tagName}> at position ${this.pos}`);
}
} else {
throw new Error(`Unterminated element <${tagName}> starting at position ${start}`);
}
}
return new XmlElement(tagName, attributes, children, attrTrailingWs, selfClosing, closeTagWs);
}
// Reads a name (letters, digits, underscore, hyphen, colon, period).
readName(): string {
const start = this.pos;
while (this.pos < this.input.length && /[A-Za-z0-9_\-.:\[\]*()#@]/.test(this.input[this.pos])) {
this.pos++;
}
return this.input.substring(start, this.pos);
}
// Reads a run of whitespace characters.
readWhitespace(): string {
const start = this.pos;
while (this.pos < this.input.length && /\s/.test(this.input[this.pos])) {
this.pos++;
}
return this.input.substring(start, this.pos);
}
// Helper: check if input at current position starts with any string in the list.
startsWithAny(strings: string[]): boolean {
for (const s of strings) {
if (this.input.startsWith(s, this.pos)) {
return true;
}
}
return false;
}
peek(): string {
return this.input[this.pos];
}
}