CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/npm-xmldom--xmldom

A pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module

Overview
Eval results
Files

parsing.mddocs/

XML/HTML Parsing

Core parsing functionality for converting XML and HTML strings into navigable DOM documents with configurable error handling and standards compliance.

Capabilities

DOMParser Class

The main parser class that converts XML/HTML strings into DOM Document objects.

/**
 * Parses XML/HTML source code from strings into DOM Documents
 * Supports configuration options for error handling and parsing behavior
 */
class DOMParser {
  constructor(options?: DOMParserOptions);
  parseFromString(source: string, mimeType: string): Document;
}

interface DOMParserOptions {
  /** Enable line/column position tracking for parsed nodes (default: true) */
  locator?: boolean;
  /** Custom line ending normalization function */
  normalizeLineEndings?: (source: string) => string;
  /** Custom error handler for parsing warnings, errors, and fatal errors */
  onError?: ErrorHandlerFunction;
  /** Default XML namespaces to assume during parsing */
  xmlns?: Readonly<Record<string, string | null | undefined>>;
  
  // Advanced/Internal Options
  /** @private - Custom Object.assign implementation for internal use */
  assign?: typeof Object.assign;
  /** @private - Custom DOM handler for internal testing */
  domHandler?: unknown;
  /** @deprecated - Use onError instead. Legacy error handler for backwards compatibility */
  errorHandler?: ErrorHandlerFunction;
}

interface ErrorHandlerFunction {
  (level: 'warning' | 'error' | 'fatalError', msg: string, context: any): void;
}

Usage Examples:

const { DOMParser } = require('@xmldom/xmldom');

// Basic parsing
const parser = new DOMParser();
const doc = parser.parseFromString('<root><child>content</child></root>', 'text/xml');

// Parsing with options
const parserWithOptions = new DOMParser({
  locator: true, // Enable line/column tracking
  onError: (level, message) => {
    console.log(`Parse ${level}: ${message}`);
  },
  xmlns: {
    '': 'http://example.com/default', // Default namespace
    'custom': 'http://example.com/custom'
  }
});

// Parse HTML
const htmlDoc = parser.parseFromString('<html><body><p>Hello</p></body></html>', 'text/html');

// Parse with different MIME types
const xmlDoc = parser.parseFromString(xmlString, 'application/xml');
const svgDoc = parser.parseFromString(svgString, 'image/svg+xml');

Supported MIME Types

/** All MIME types supported by DOMParser.parseFromString */
const MIME_TYPE = {
  /** HTML document parsing with HTML-specific behavior */
  HTML: 'text/html',
  /** Standard XML document parsing */
  XML_APPLICATION: 'application/xml',
  /** Alternative XML MIME type */
  XML_TEXT: 'text/xml',
  /** XHTML document with XML parsing but HTML namespace */
  XML_XHTML_APPLICATION: 'application/xhtml+xml',
  /** SVG document parsing */
  XML_SVG_IMAGE: 'image/svg+xml'
};

/**
 * Validates if a MIME type is supported by DOMParser
 * @param mimeType - The MIME type to validate
 * @returns True if the MIME type is supported
 */
function isValidMimeType(mimeType: string): boolean;

/**
 * Checks if MIME type indicates HTML parsing mode
 * @param mimeType - The MIME type to check
 * @returns True if MIME type is 'text/html'
 */
function isHTMLMimeType(mimeType: string): boolean;

/**
 * Checks if MIME type should use default HTML namespace
 * @param mimeType - The MIME type to check
 * @returns True for HTML and XHTML MIME types
 */
function hasDefaultHTMLNamespace(mimeType: string): boolean;

Line Ending Normalization

/**
 * Normalizes line endings according to XML specification
 * Converts various line ending formats to single LF character
 * @param input - Input string with potentially mixed line endings
 * @returns String with normalized line endings
 */
function normalizeLineEndings(input: string): string;

Usage Example:

const { normalizeLineEndings } = require('@xmldom/xmldom');

// Normalize mixed line endings
const normalized = normalizeLineEndings('line1\r\nline2\rline3\nline4');
// Result: 'line1\nline2\nline3\nline4'

Error Handling Functions

/**
 * Error handler that stops parsing on any error level
 * Throws ParseError immediately when called
 */
function onErrorStopParsing(): never;

/**
 * Error handler that stops parsing on warnings and errors
 * More permissive than onErrorStopParsing
 */
function onWarningStopParsing(): never;

Usage Example:

const { DOMParser, onErrorStopParsing } = require('@xmldom/xmldom');

// Strict parsing that stops on any error
const strictParser = new DOMParser({
  onError: onErrorStopParsing
});

try {
  const doc = strictParser.parseFromString('<invalid><xml>', 'text/xml');
} catch (error) {
  console.log('Parsing failed:', error.message);
}

Advanced Usage

Custom Error Handling

const parser = new DOMParser({
  onError: (level, message, context) => {
    switch (level) {
      case 'warning':
        console.warn('XML Warning:', message);
        break;
      case 'error':
        console.error('XML Error:', message);
        break;
      case 'fatalError':
        throw new Error(`Fatal XML Error: ${message}`);
    }
  }
});

Namespace Configuration

const parser = new DOMParser({
  xmlns: {
    '': 'http://example.com/default',
    'ns1': 'http://example.com/namespace1',
    'ns2': 'http://example.com/namespace2'
  }
});

const doc = parser.parseFromString(`
  <root xmlns:custom="http://custom.com">
    <ns1:element>Content</ns1:element>
    <custom:element>More content</custom:element>
  </root>
`, 'text/xml');

Location Tracking

const parser = new DOMParser({ locator: true });
const doc = parser.parseFromString(`<root>
  <child>content</child>
</root>`, 'text/xml');

const child = doc.getElementsByTagName('child')[0];
console.log(`Element at line ${child.lineNumber}, column ${child.columnNumber}`);
tessl i tessl/npm-xmldom--xmldom@0.9.0

docs

constants-utilities.md

dom-manipulation.md

error-handling.md

index.md

parsing.md

serialization.md

tile.json