@eksml/xml
v0.1.2
Published
Fast, lightweight XML/HTML parser, serializer, and streaming toolkit
Maintainers
Readme
Eksml
A fast, lightweight XML/HTML parser, serializer, and streaming toolkit for JavaScript and TypeScript. Import only what you need — tree parsing, SAX streaming, object conversion, or serialization — each as a standalone export.
Built on the same core parsing architecture as tXml by Tobias Nickel, Eksml improves the performance and extends it with additional features.
Installation
pnpm add @eksml/xmlnpm install @eksml/xmlyarn add @eksml/xmlEksml is ESM-only. It requires Node.js 18+ and a runtime that supports ES modules. There are no CommonJS exports.
Quick Start
import { parse } from '@eksml/xml/parser';
import { write } from '@eksml/xml/writer';
const dom = parse('<root><item id="1">Hello</item></root>');
const str = write(dom);API
import { parse } from '@eksml/xml/parser';
const dom = parse('<root><item>Hello</item></root>');ParseOptions
TNode
interface TNode {
tagName: string;
attributes: Record<string, string | null> | null;
children: (TNode | string)[];
}attributesisnullwhen the element has no attributes.- Attribute values are
stringfor valued attributes,nullfor boolean attributes (e.g.<input disabled>).
write(input, options?)
Serialize a DOM tree, lossy object, or lossless entries back to an XML/HTML string. Input format is auto-detected — no manual conversion needed.
import { write } from '@eksml/xml/writer';
// DOM input
const xml = write(dom);
const pretty = write(dom, { pretty: true });
const html = write(dom, { html: true, entities: true });
// Lossy input — converted to DOM automatically
const fromObj = write({ user: { name: 'Alice', age: 30 } });
// -> '<user><name>Alice</name><age>30</age></user>'
// Lossless input — converted to DOM automatically
const fromEntries = write([
{ user: [{ name: ['Alice'] }, { role: ['admin'] }] },
]);
// -> '<user><name>Alice</name><role>admin</role></user>'WriterOptions
createSaxParser(options?)
A high-performance EventEmitter-style SAX parser. Feed it chunks of XML and receive events via .on() / .off() handlers. Handlers can be added and removed dynamically at any time.
import { createSaxParser } from '@eksml/xml/sax';
const parser = createSaxParser();
parser.on('openTag', (tagName, attributes) => {
console.log('opened:', tagName, attributes);
});
parser.on('text', (text) => {
console.log('text:', text);
});
parser.write('<root><item>1</item>');
parser.write('<item>2</item></root>');
parser.close();
// Remove a handler
parser.off('openTag', myHandler);SaxParserOptions
SAX Events
new XmlParseStream(options?)
A Web Streams TransformStream that parses XML chunks into TNode subtrees. Works in browsers, Node.js 18+, Deno, and Bun. Follows the platform stream class convention (TextDecoderStream, DecompressionStream, etc.).
import { XmlParseStream } from '@eksml/xml/stream';
const response = await fetch('/feed.xml');
const reader = response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(new XmlParseStream())
.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(value); // TNode or string
}XmlParseStreamOptions
The select option is particularly useful for large feeds:
// Emit each <item> independently instead of waiting for the root to close
const stream = new XmlParseStream({ select: 'item' });lossy(input, options?)
Convert XML into compact JavaScript objects. Ideal when you need a simple JS representation and don't care about preserving document order between mixed siblings.
input is string | (TNode | string)[] — pass a raw XML string, or a pre-parsed DOM array (from parse() or stream()).
import { lossy } from '@eksml/xml/lossy';
lossy('<user><name>Alice</name><age>30</age></user>');
// => { user: { name: "Alice", age: "30" } }- Text-only elements become string values
- Empty/void elements become
null - Attributes are
$-prefixed keys (e.g.$href) - Repeated same-name siblings become arrays
- Mixed content (text interleaved with elements) is stored in a
$$array
[!note] Accepts the same ParseOptions as parse().
lossless(input, options?)
Convert XML into an order-preserving JSON-friendly structure. Every node, attribute, text segment, and comment is represented in document order.
input is string | (TNode | string)[] — pass a raw XML string, or a pre-parsed DOM array (from parse() or stream()).
import { lossless } from '@eksml/xml/lossless';
lossless('<user id="1"><name>Alice</name></user>');
// => [{ user: [{ $attr: { id: "1" } }, { name: [{ $text: "Alice" }] }] }]Each entry type:
- Element:
{ tagName: children[] } - Text:
{ $text: "..." } - Attributes:
{ $attr: { ... } }(first child of its element) - Comment:
{ $comment: "..." }
[!note] Accepts the same ParseOptions as parse().
fromLossy(input) / fromLossless(entries)
Convert lossy or lossless representations back into TNode DOM trees.
Note:
write()auto-detects lossy and lossless inputs, so you rarely need these directly. They're useful when you want the DOM tree for inspection or further manipulation before serializing.
import { fromLossy } from '@eksml/xml/from-lossy';
import { fromLossless } from '@eksml/xml/from-lossless';
import { write } from '@eksml/xml/writer';
// Explicit conversion (when you need the DOM tree)
const dom = fromLossy({ user: { name: 'Alice' } });
write(dom); // => '<user><name>Alice</name></user>'
// Or just pass lossy/lossless directly to write()
write({ user: { name: 'Alice' } }); // same resultUtilities
import {
filter,
getElementById,
getElementsByClassName,
toContentString,
isTextNode,
isElementNode,
HTML_VOID_ELEMENTS,
HTML_RAW_CONTENT_TAGS,
} from '@eksml/xml/utilities';Benchmarks
Eksml is consistently the fastest across parsing, streaming, and serialization. Benchmarks run via Vitest bench against real-world XML fixtures from ~100 B to ~30 KB.
- DOM parsing: 1.2-1.5x faster than tXml, 3-4x faster than htmlparser2, 7-15x faster than fast-xml-parser/xml2js/xmldom
- SAX streaming: 1.6-2.5x faster than htmlparser2/saxes, 3-6x faster than sax
- Raw tokenization: 2-2.5x faster than saxes, 2-3x faster than htmlparser2, 4-6x faster than sax
- Serialization: Trades top position with tXml; both are 3-7x faster than xmldom and 7-13x faster than fast-xml-parser/xml2js
Full results with per-fixture op/s tables: BENCHMARKS.md
Run similar benchmarks in your browser: Interactive benchmark
HTML Support
Eksml can parse and serialize HTML, but it is not an HTML spec-compliant parser. It does not implement the WHATWG HTML parsing algorithm — there is no tokenizer state machine, no tree construction stage, no implicit element insertion, and no error recovery for malformed markup.
What Eksml does provide is a set of HTML-aware options that cover the most common differences between XML and HTML:
- Void elements —
<br>,<img>,<input>, etc. are recognized as self-closing whenhtml: trueis set (or when you provide a customselfClosingTagslist). The full list is exported asHTML_VOID_ELEMENTSfrom@eksml/xml/utilities. - Raw content tags —
<script>and<style>content is treated as raw text (not parsed for child elements) whenhtml: trueis set. Customizable viarawContentTags. Exported asHTML_RAW_CONTENT_TAGS. - Entity encoding — The writer uses HTML named entities (e.g.
,©) instead of numeric references whenhtml: trueandentities: trueare both set. - Serialization style — Void elements serialize as
<br>instead of<br/>in HTML mode.
This is sufficient for well-formed HTML and most real-world documents. However, Eksml will not handle things like:
- Optional closing tags (
<li>without</li>,<p>auto-closed by a sibling<p>) - Implicit elements (
<html>,<head>,<body>inserted by the spec when missing) - Misnested formatting tags (the adoption agency algorithm)
<table>foster parenting
If you need full HTML spec compliance, use a dedicated HTML parser like parse5 or the browser's built-in DOMParser.
Acknowledgments
Eksml's DOM parser is built on the work of Tobias Nickel and his tXml library. The core parsing architecture, a single-pass, position-tracking string scanner that builds the tree as it goes, is what makes both libraries so fast. tXml demonstrated that you don't need a separate tokenizer-then-tree-builder pipeline to parse XML at high speed, and Eksml carries that insight forward.
Eksml extends tXml's foundation with:
- A high-performance SAX streaming engine with an EventEmitter-style API (
createSaxParser) - A Web Streams
TransformStreamfor incremental parsing (XmlParseStream) - Lossy and lossless JSON converters with round-trip support
- HTML-aware parsing and serialization (void elements, raw content tags, entity encoding)
- Strict mode validation
- Entity decoding (XML and full HTML named entities)
Thank you, Tobias, for the elegant approach that made all of this possible.
Limitations
Eksml optimizes for speed and simplicity, which means it intentionally does not cover every XML use case:
- Not a validating parser. Eksml does not validate against DTDs or XML Schema. It parses structure, not semantics.
- No namespace support. Namespace prefixes are preserved in tag and attribute names (e.g.
soap:Envelope) but not resolved to URIs. There is no namespace-aware API. - No XPath or CSS selectors. Querying uses simple functions like
filter(),getElementById(), andgetElementsByClassName(). For complex queries, use the DOM output with a dedicated query library. - Entity decoding is opt-in. By default, entities like
&and are left as-is in text and attribute values. Passentities: trueto decode them. - Not a drop-in replacement for the W3C DOM.
TNodeis a plain object withtagName,attributes, andchildren-- not aNode/Element/Documentwith methods likequerySelector,parentNode, etc. - Single-threaded. Parsing runs synchronously on the calling thread. For CPU-bound workloads with very large documents, consider offloading to a Web Worker.
License
MIT
