Skip to content

Parsing XML

Lanexio Parser implements XML 1.0 5th Edition with optional DTD validation. The parser handles multi-byte encodings, external entities, and the full W3C XML conformance suite.

  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser-grammar-xml
  2. Parse an XML document.

    import { parseXml } from '@lanexio/parser-grammar-xml';
    const encoder = new TextEncoder();
    const tree = parseXml(encoder.encode(`
    <?xml version="1.0" encoding="UTF-8"?>
    <catalog>
    <book id="bk101">
    <title>XML Guide</title>
    <price>44.95</price>
    </book>
    </catalog>
    `));

Enable DTD validation by providing an ExternalResolver:

import { parseXml, ExternalResolver } from '@lanexio/parser-grammar-xml';
const resolver: ExternalResolver = {
async resolveEntity(systemId: string, publicId?: string) {
const res = await fetch(systemId);
return new Uint8Array(await res.arrayBuffer());
},
};
const tree = parseXml(documentBytes, { resolver });

When no resolver is provided, the parser parses without DTD validation — entities are preserved as text.

Elements, attributes, text nodes, comments, PIs, CDATA sections, and doctype declarations are all represented in the flat AST. The tree preserves the document’s hierarchical structure.

const cursor = tree.cursor();
cursor.gotoFirstChild(); // XmlDeclaration or DocumentElement
while (cursor.gotoNextSibling()) {
console.log(cursor.current.kind);
}