Skip to content

evoactivity/eksml

Repository files navigation

Eksml

Eksml

CI coverage npm license

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.

Try the interactive demo

Installation

pnpm add @eksml/xml
npm install @eksml/xml
yarn add @eksml/xml

Eksml 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

Option Type Default Description
pos number 0 Starting character position in the string
html boolean false Enable HTML mode (sets void element and raw content tag defaults)
selfClosingTags string[] [] / HTML voids Tag names treated as self-closing void elements
rawContentTags string[] [] / ['script','style'] Tag names whose content is raw text (not parsed)
keepComments boolean false Include XML/HTML comments in the output tree
trimWhitespace boolean false Trim text nodes and discard whitespace-only text
strict boolean false Throw on malformed XML instead of recovering silently
entities boolean false Decode XML/HTML entities in text and attributes
attrName string 'id' Attribute name to search for (used with attrValue)
attrValue string -- Regex pattern to match attribute values (fast-path filter)
filter (node, index, depth, path) => boolean -- Predicate to filter nodes during parsing

TNode

interface TNode {
  tagName: string;
  attributes: Record<string, string | null> | null;
  children: (TNode | string)[];
}
  • attributes is null when the element has no attributes.
  • Attribute values are string for valued attributes, null for 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

Option Type Default Description
pretty boolean | string false Pretty-print with indentation. true uses 2 spaces; a string value is used as the indent (e.g. '\t').
entities boolean false Encode special characters as XML/HTML entities
html boolean false HTML mode: void elements emit as <br> instead of <br/>, and HTML named entities are used when entities is also true

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

Option Type Default Description
html boolean false Enable HTML mode (sets void element and raw content tag defaults)
selfClosingTags string[] [] / HTML voids Tag names treated as self-closing void elements
rawContentTags string[] [] / ['script','style'] Tag names whose content is raw text

SAX Events

Event Handler signature Description
openTag (tagName, attributes) => void Opening tag with parsed attributes
closeTag (tagName) => void Closing tag
text (text) => void Text content between tags
cdata (data) => void CDATA section content
comment (comment) => void Comment (full <!-- ... --> string including delimiters)
processingInstruction (name, body) => void Processing instruction
doctype (tagName, attributes) => void DOCTYPE declaration

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

Option Type Default Description
offset number | string 0 Starting byte offset — skip this many leading characters. When a string is passed, its .length is used.
html boolean false Enable HTML mode
selfClosingTags string[] [] / HTML voids Tag names treated as self-closing
rawContentTags string[] [] / ['script','style'] Tag names whose content is raw text
keepComments boolean false Include comments in the output
select string | string[] -- Emit only elements matching these tag names as they close, regardless of nesting depth
output 'dom' | 'lossy' | 'lossless' 'dom' Output format — 'dom' emits TNode | string, 'lossy' emits LossyValue, 'lossless' emits LosslessEntry

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 result

Utilities

import {
  filter,
  getElementById,
  getElementsByClassName,
  toContentString,
  isTextNode,
  isElementNode,
  HTML_VOID_ELEMENTS,
  HTML_RAW_CONTENT_TAGS,
} from '@eksml/xml/utilities';
Export Description
filter(input, predicate) Recursively walk a tree and return all TNodes matching a predicate
getElementById(input, id) Find an element by its id attribute
getElementsByClassName(input, className) Find elements by class name (supports multi-class attributes)
toContentString(node) Extract concatenated text content from a node or tree
isTextNode(node) Type guard: node is string
isElementNode(node) Type guard: node is TNode
HTML_VOID_ELEMENTS Standard HTML void element tag names
HTML_RAW_CONTENT_TAGS HTML raw content tag names (script, style)

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 when html: true is set (or when you provide a custom selfClosingTags list). The full list is exported as HTML_VOID_ELEMENTS from @eksml/xml/utilities.
  • Raw content tags<script> and <style> content is treated as raw text (not parsed for child elements) when html: true is set. Customizable via rawContentTags. Exported as HTML_RAW_CONTENT_TAGS.
  • Entity encoding — The writer uses HTML named entities (e.g. &nbsp;, &copy;) instead of numeric references when html: true and entities: true are 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 TransformStream for 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(), and getElementsByClassName(). For complex queries, use the DOM output with a dedicated query library.
  • Entity decoding is opt-in. By default, entities like &amp; and &#x20; are left as-is in text and attribute values. Pass entities: true to decode them.
  • Not a drop-in replacement for the W3C DOM. TNode is a plain object with tagName, attributes, and children -- not a Node/Element/Document with methods like querySelector, 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

About

Fast XML Parsing & Writing

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors