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.
Quick start
Section titled “Quick start”-
Install the package.
Terminal window pnpm add @lanexio/parser-grammar-xmlTerminal window npm install @lanexio/parser-grammar-xmlTerminal window yarn add @lanexio/parser-grammar-xml -
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>`));
DTD validation
Section titled “DTD validation”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.
Inspecting the tree
Section titled “Inspecting the tree”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);}