Saxes Streaming XML Parser

6.0.0 · active · verified Sun Apr 19

Saxes is an evented, streaming XML parser for JavaScript, currently at version 6.0.0. It is a modern, stricter, and significantly faster fork of the original `sax` library, designed primarily for Node.js environments (requiring Node.js >=12.22.7) but also functional in browsers. Its core differentiator is a strong adherence to XML 1.0/1.1 and Namespaces in XML 1.0/1.1 well-formedness rules, unlike `sax` which tolerates malformed structures. This makes `saxes` unsuitable for HTML or pseudo-XML parsing, as it will explicitly report well-formedness errors. While it is a non-validating parser, it aims to catch all malformed constructs outside of thorough DTD validation. `saxes` does not include a `Stream` API, a notable departure from its `sax` predecessor, and its `onerror` handler defaults to throwing errors, which can be overridden. The project is actively maintained, with a focus on performance and strict conformance to XML specifications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic parsing of an XML string, handling open tags, text content, close tags, and errors using event listeners. It shows both attributes and CDATA sections.

import { SaxesParser } from 'saxes';

const xmlString = `<root>
  <item id="1">Hello &amp; World!</item>
  <item id="2"><![CDATA[<tag>content</tag>]]></item>
</root>`;

const parser = new SaxesParser();

parser.on('error', (err) => {
  console.error('XML Parsing Error:', err.message);
  // The default onerror handler throws, so subsequent data calls might not happen if not caught.
});

parser.on('opentag', (node) => {
  console.log(`Opened tag: ${node.name} with attributes:`, node.attributes);
});

parser.on('text', (text) => {
  if (text.trim().length > 0) {
    console.log(`Text content: '${text.trim()}'`);
  }
});

parser.on('closetag', (nodeName) => {
  console.log(`Closed tag: ${nodeName}`);
});

parser.on('end', () => {
  console.log('Finished parsing XML.');
});

try {
  parser.write(xmlString).close();
} catch (e) {
  // Catch errors if the default onerror handler is active and throws
  console.error('Caught error during write/close:', e.message);
}

view raw JSON →