npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@eksml/xml

v0.1.2

Published

Fast, lightweight XML/HTML parser, serializer, and streaming toolkit

Readme

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

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


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 result

Utilities

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 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