0
# Constants and Utilities
1
2
Standard DOM constants, MIME type definitions, namespace URIs, and utility functions for validation and type checking in XML processing applications.
3
4
## Capabilities
5
6
### MIME Type Constants
7
8
Supported MIME types for XML/HTML parsing with validation utilities.
9
10
```javascript { .api }
11
/**
12
* Standard MIME types supported by DOMParser
13
*/
14
const MIME_TYPE = {
15
/** HTML document parsing with HTML-specific behavior */
16
HTML: 'text/html',
17
/** Standard XML document parsing */
18
XML_APPLICATION: 'application/xml',
19
/** Alternative XML MIME type */
20
XML_TEXT: 'text/xml',
21
/** XHTML document with XML parsing but HTML namespace */
22
XML_XHTML_APPLICATION: 'application/xhtml+xml',
23
/** SVG document parsing */
24
XML_SVG_IMAGE: 'image/svg+xml'
25
};
26
27
/**
28
* Validates if a MIME type is supported by DOMParser
29
* @param mimeType - The MIME type string to validate
30
* @returns True if the MIME type is supported for parsing
31
*/
32
function isValidMimeType(mimeType: string): boolean;
33
34
/**
35
* Checks if MIME type indicates HTML parsing mode
36
* @param mimeType - The MIME type to check
37
* @returns True if MIME type is 'text/html'
38
*/
39
function isHTMLMimeType(mimeType: string): boolean;
40
41
/**
42
* Checks if MIME type should use default HTML namespace
43
* @param mimeType - The MIME type to check
44
* @returns True for 'text/html' and 'application/xhtml+xml'
45
*/
46
function hasDefaultHTMLNamespace(mimeType: string): boolean;
47
```
48
49
**Usage Examples:**
50
51
```javascript
52
const { MIME_TYPE, isValidMimeType, isHTMLMimeType } = require('@xmldom/xmldom');
53
54
// Validate MIME types before parsing
55
const userMimeType = 'application/xml';
56
if (isValidMimeType(userMimeType)) {
57
console.log('Valid MIME type for parsing');
58
}
59
60
// Check for HTML parsing behavior
61
if (isHTMLMimeType(userMimeType)) {
62
console.log('Will parse as HTML document');
63
} else {
64
console.log('Will parse as XML document');
65
}
66
67
// Use constants instead of string literals
68
const parser = new DOMParser();
69
const xmlDoc = parser.parseFromString(xmlString, MIME_TYPE.XML_APPLICATION);
70
const htmlDoc = parser.parseFromString(htmlString, MIME_TYPE.HTML);
71
const svgDoc = parser.parseFromString(svgString, MIME_TYPE.XML_SVG_IMAGE);
72
```
73
74
### Namespace Constants
75
76
Standard XML namespace URIs used in web technologies.
77
78
```javascript { .api }
79
/**
80
* Standard XML namespaces used in web technologies
81
*/
82
const NAMESPACE = {
83
/** XHTML namespace */
84
HTML: 'http://www.w3.org/1999/xhtml',
85
/** SVG namespace */
86
SVG: 'http://www.w3.org/2000/svg',
87
/** XML namespace for xml: prefixed attributes */
88
XML: 'http://www.w3.org/XML/1998/namespace',
89
/** XMLNS namespace for namespace declarations */
90
XMLNS: 'http://www.w3.org/2000/xmlns/'
91
};
92
```
93
94
**Usage Examples:**
95
96
```javascript
97
const { NAMESPACE, DOMParser } = require('@xmldom/xmldom');
98
99
const parser = new DOMParser();
100
const doc = parser.parseFromString('<root></root>', 'text/xml');
101
102
// Create elements with standard namespaces
103
const htmlElement = doc.createElementNS(NAMESPACE.HTML, 'div');
104
const svgElement = doc.createElementNS(NAMESPACE.SVG, 'circle');
105
106
// Set namespace-aware attributes
107
htmlElement.setAttributeNS(NAMESPACE.XML, 'xml:lang', 'en');
108
svgElement.setAttributeNS(null, 'r', '50');
109
110
// Check element namespaces
111
if (htmlElement.namespaceURI === NAMESPACE.HTML) {
112
console.log('Element is in HTML namespace');
113
}
114
```
115
116
### Object Utilities
117
118
Utility functions for object manipulation and compatibility.
119
120
```javascript { .api }
121
/**
122
* Object.assign ponyfill for merging objects
123
* Provides Object.assign functionality in ES5 environments
124
* @param target - Target object to merge properties into
125
* @param source - Source object to copy properties from
126
* @returns Target object with merged properties
127
* @throws TypeError if target is not an object
128
*/
129
function assign<T, S>(target: T, source: S): T & S;
130
```
131
132
**Usage Examples:**
133
134
```javascript
135
const { assign } = require('@xmldom/xmldom');
136
137
// Merge configuration objects
138
const defaultOptions = {
139
locator: true,
140
normalizeLineEndings: true
141
};
142
143
const userOptions = {
144
onError: (level, msg) => console.log(`${level}: ${msg}`)
145
};
146
147
const mergedOptions = assign(defaultOptions, userOptions);
148
// Result: { locator: true, normalizeLineEndings: true, onError: function }
149
150
// Use in DOMParser construction
151
const parser = new DOMParser(mergedOptions);
152
```
153
154
### Text Processing Utilities
155
156
Functions for handling and normalizing text content according to XML standards.
157
158
```javascript { .api }
159
/**
160
* Normalizes line endings according to XML specification
161
* Handles various line ending formats and Unicode newline characters
162
* @param input - Input string with potentially mixed line endings
163
* @returns String with normalized line endings (LF only)
164
*/
165
function normalizeLineEndings(input: string): string;
166
```
167
168
**Usage Examples:**
169
170
```javascript
171
const { normalizeLineEndings } = require('@xmldom/xmldom');
172
173
// Handle text with mixed line endings
174
const mixedText = 'line1\r\nline2\rline3\nline4\u2028line5\u2029line6';
175
const normalized = normalizeLineEndings(mixedText);
176
console.log(normalized); // 'line1\nline2\nline3\nline4\nline5\nline6'
177
178
// Use in custom parsing options
179
const parser = new DOMParser({
180
normalizeLineEndings: (source) => {
181
// Custom normalization with additional processing
182
const normalized = normalizeLineEndings(source);
183
return normalized.replace(/\t/g, ' '); // Convert tabs to spaces
184
}
185
});
186
```
187
188
### Node Type Constants
189
190
Standard DOM node type constants for identifying node types.
191
192
```javascript { .api }
193
/**
194
* Standard DOM node type constants
195
*/
196
const NodeType = {
197
ELEMENT_NODE: 1,
198
ATTRIBUTE_NODE: 2,
199
TEXT_NODE: 3,
200
CDATA_SECTION_NODE: 4,
201
ENTITY_REFERENCE_NODE: 5,
202
ENTITY_NODE: 6,
203
PROCESSING_INSTRUCTION_NODE: 7,
204
COMMENT_NODE: 8,
205
DOCUMENT_NODE: 9,
206
DOCUMENT_TYPE_NODE: 10,
207
DOCUMENT_FRAGMENT_NODE: 11,
208
NOTATION_NODE: 12
209
};
210
211
// Also available as static properties on Node class
212
Node.ELEMENT_NODE; // 1
213
Node.TEXT_NODE; // 3
214
Node.COMMENT_NODE; // 8
215
// etc.
216
```
217
218
**Usage Examples:**
219
220
```javascript
221
const { DOMParser, Node } = require('@xmldom/xmldom');
222
223
function processNode(node) {
224
switch (node.nodeType) {
225
case Node.ELEMENT_NODE:
226
console.log(`Element: ${node.tagName}`);
227
break;
228
case Node.TEXT_NODE:
229
console.log(`Text: ${node.data}`);
230
break;
231
case Node.COMMENT_NODE:
232
console.log(`Comment: ${node.data}`);
233
break;
234
case Node.DOCUMENT_NODE:
235
console.log('Document root');
236
break;
237
default:
238
console.log(`Other node type: ${node.nodeType}`);
239
}
240
}
241
242
// Walk through all nodes in a document
243
function walkNodes(node) {
244
processNode(node);
245
246
if (node.childNodes) {
247
for (let i = 0; i < node.childNodes.length; i++) {
248
walkNodes(node.childNodes[i]);
249
}
250
}
251
}
252
```
253
254
### Document Position Constants
255
256
Constants for comparing relative positions of nodes in the document tree.
257
258
```javascript { .api }
259
/**
260
* Constants for Node.compareDocumentPosition() return values
261
*/
262
const DocumentPosition = {
263
DISCONNECTED: 0x01, // Nodes are not in the same tree
264
PRECEDING: 0x02, // Other node precedes this node
265
FOLLOWING: 0x04, // Other node follows this node
266
CONTAINS: 0x08, // Other node contains this node
267
CONTAINED_BY: 0x10, // Other node is contained by this node
268
IMPLEMENTATION_SPECIFIC: 0x20 // Implementation-specific ordering
269
};
270
271
// Also available as static properties on Node class
272
Node.DOCUMENT_POSITION_DISCONNECTED; // 0x01
273
Node.DOCUMENT_POSITION_PRECEDING; // 0x02
274
// etc.
275
```
276
277
**Usage Examples:**
278
279
```javascript
280
const { DOMParser, Node } = require('@xmldom/xmldom');
281
282
const parser = new DOMParser();
283
const doc = parser.parseFromString('<root><a></a><b></b></root>', 'text/xml');
284
285
const nodeA = doc.getElementsByTagName('a')[0];
286
const nodeB = doc.getElementsByTagName('b')[0];
287
288
const position = nodeA.compareDocumentPosition(nodeB);
289
290
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
291
console.log('Node B follows Node A');
292
}
293
294
if (position & Node.DOCUMENT_POSITION_DISCONNECTED) {
295
console.log('Nodes are in different documents');
296
}
297
```
298
299
### Validation Utilities
300
301
Additional utility functions for validation and type checking.
302
303
```javascript { .api }
304
/**
305
* Type guard functions and validation utilities
306
* These are primarily used internally but may be useful for applications
307
*/
308
309
// Example usage patterns (these represent the types of utilities available)
310
function isElementNode(node: Node): node is Element;
311
function isTextNode(node: Node): node is Text;
312
function isDocumentNode(node: Node): node is Document;
313
```
314
315
**Usage Examples:**
316
317
```javascript
318
// Custom validation functions using node types
319
function isElementNode(node) {
320
return node && node.nodeType === Node.ELEMENT_NODE;
321
}
322
323
function isTextNode(node) {
324
return node && node.nodeType === Node.TEXT_NODE;
325
}
326
327
function getElementChildren(parent) {
328
const children = [];
329
for (let i = 0; i < parent.childNodes.length; i++) {
330
const child = parent.childNodes[i];
331
if (isElementNode(child)) {
332
children.push(child);
333
}
334
}
335
return children;
336
}
337
338
function getTextContent(node) {
339
if (isTextNode(node)) {
340
return node.data;
341
}
342
343
let text = '';
344
for (let i = 0; i < node.childNodes.length; i++) {
345
text += getTextContent(node.childNodes[i]);
346
}
347
return text;
348
}
349
```
350
351
### Error Handler Utilities
352
353
Predefined error handling functions for common parsing scenarios.
354
355
```javascript { .api }
356
/**
357
* Predefined error handlers for DOMParser
358
*/
359
360
/**
361
* Error handler that stops parsing on any error level (error or fatalError)
362
* Throws ParseError to halt parsing immediately
363
*/
364
function onErrorStopParsing(): void | never;
365
366
/**
367
* Error handler that stops parsing on any level including warnings
368
* Most restrictive error handling mode
369
*/
370
function onWarningStopParsing(): never;
371
```
372
373
**Usage Examples:**
374
375
```javascript
376
const {
377
DOMParser,
378
onErrorStopParsing,
379
onWarningStopParsing
380
} = require('@xmldom/xmldom');
381
382
// Strict parsing - stops on errors
383
const strictParser = new DOMParser({
384
onError: onErrorStopParsing
385
});
386
387
// Very strict parsing - stops on warnings too
388
const veryStrictParser = new DOMParser({
389
onError: onWarningStopParsing
390
});
391
392
// Custom error handling with fallback
393
const parser = new DOMParser({
394
onError: (level, message, context) => {
395
if (level === 'fatalError') {
396
onErrorStopParsing(); // Delegate to standard handler
397
} else {
398
console.warn(`XML ${level}: ${message}`);
399
}
400
}
401
});
402
```
403
404
### Integration Examples
405
406
Using constants and utilities together in real applications:
407
408
```javascript
409
const {
410
DOMParser,
411
XMLSerializer,
412
MIME_TYPE,
413
NAMESPACE,
414
Node,
415
isValidMimeType,
416
normalizeLineEndings,
417
assign
418
} = require('@xmldom/xmldom');
419
420
// Configuration-driven XML processing
421
function createConfiguredParser(config) {
422
const defaultConfig = {
423
locator: true,
424
normalizeLineEndings: normalizeLineEndings,
425
onError: (level, msg) => console.log(`${level}: ${msg}`)
426
};
427
428
const finalConfig = assign(defaultConfig, config);
429
return new DOMParser(finalConfig);
430
}
431
432
// Safe document creation with validation
433
function createDocument(xmlString, mimeType = MIME_TYPE.XML_APPLICATION) {
434
if (!isValidMimeType(mimeType)) {
435
throw new Error(`Unsupported MIME type: ${mimeType}`);
436
}
437
438
const parser = createConfiguredParser({
439
xmlns: {
440
'': NAMESPACE.HTML, // Default to HTML namespace
441
'svg': NAMESPACE.SVG
442
}
443
});
444
445
return parser.parseFromString(xmlString, mimeType);
446
}
447
448
// Node type-aware processing
449
function processDocument(doc) {
450
const serializer = new XMLSerializer();
451
452
function processNode(node) {
453
switch (node.nodeType) {
454
case Node.ELEMENT_NODE:
455
if (node.namespaceURI === NAMESPACE.SVG) {
456
console.log('Processing SVG element:', node.tagName);
457
}
458
break;
459
case Node.TEXT_NODE:
460
if (node.data.trim()) {
461
console.log('Text content:', node.data.trim());
462
}
463
break;
464
}
465
466
// Process children
467
for (let i = 0; i < node.childNodes.length; i++) {
468
processNode(node.childNodes[i]);
469
}
470
}
471
472
processNode(doc);
473
return serializer.serializeToString(doc);
474
}
475
```