2026-09-29 16:10:12 +00:00
2026-09-29 16:10:12 +00:00
2026-09-29 16:10:12 +00:00
2020-10-24 15:47:12 +00:00
2026-09-29 16:10:12 +00:00
2026-09-29 15:56:24 +00:00

@push.rocks/smartxml

a package for creating and parsing XML formatted files, and for querying them with XPath 3.1

Install

To start using @push.rocks/smartxml in your project, you'll first need to install it. This package is distributed via npm, so you can install it by running the following command in your project's root directory:

npm install @push.rocks/smartxml --save

Usage

Getting Started

First, ensure that your project is set up to use TypeScript and ESM syntax. Then, you can import SmartXml from @push.rocks/smartxml as follows:

import { SmartXml } from '@push.rocks/smartxml';

SmartXml provides two main functionalities: parsing XML formatted strings into JavaScript objects and vice versa, creating XML formatted strings from JavaScript objects.

Parsing XML String to Object

To parse an XML string to a JavaScript object, you can use the parseXmlToObject method. This method takes an XML string as its argument and returns a JavaScript object.

Here's a simple example:

const xmlString = `
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
`;

const smartXml = new SmartXml();
const resultObject = smartXml.parseXmlToObject(xmlString);

console.log(resultObject);

Creating XML String from Object

Conversely, if you have a JavaScript object that you want to convert into an XML formatted string, you can use the createXmlFromObject method. This method accepts a JavaScript object and returns a string containing the XML representation of the object.

Here's an example:

const noteObject = {
  note: {
    to: 'Tove',
    from: 'Jani',
    heading: 'Reminder',
    body: "Don't forget me this weekend!",
  },
};

const smartXml = new SmartXml();
const xmlString = smartXml.createXmlFromObject(noteObject);

console.log(xmlString);

Advanced Usage

The SmartXml class is built on top of the fast-xml-parser library, which provides a lot of flexibility for both parsing and creation. For example, when creating XML from objects, you can control attributes, formatting, and more.

Let's look at a more complex example that includes XML attributes:

const complexObject = {
  note: {
    '@_id': '12345',
    '@_priority': 'high',
    to: 'Tove',
    from: { '@_domain': 'personal', '#text': 'Jani' },
    heading: {
      '@_style': 'bold',
      '#text': 'Reminder',
    },
    body: 'This is a special note for the weekend.',
  },
};

const smartXml = new SmartXml();
const complexXmlString = smartXml.createXmlFromObject(complexObject, {
  format: true,
});

console.log(complexXmlString);

This example demonstrates how to add attributes (using "@_attributeName": "value") and mixed content (using "#text": "text value") to your objects before converting them to XML.

XPath 3.1 and a conformant DOM

@push.rocks/smartxml/xpath carries an XPath 3.1 engine and an XML DOM. Use it when element names, namespaces and document order matter, rather than the object mapping of the main entry point.

import { parseXmlDocument, evaluateXPathToString, evaluateXPathToNodes, registerCustomXPathFunction } from '@push.rocks/smartxml/xpath';

const document = parseXmlDocument(`
  <Invoice xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
    <cbc:ID>RE-1001</cbc:ID>
  </Invoice>`);

const options = {
  namespaceResolver: (prefix: string) =>
    prefix === 'cbc' ? 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' : null,
};

evaluateXPathToString('/Invoice/cbc:ID', document, null, {}, options); // 'RE-1001'
evaluateXPathToNodes('/Invoice/*', document, null, {}, options); // [Element]

Rule languages such as Schematron declare their own helper functions. Register them once and they are callable from every expression:

registerCustomXPathFunction(
  { namespaceURI: 'https://example.com/checks', localName: 'isEven' },
  ['xs:integer'],
  'xs:boolean',
  (_context, value: number) => value % 2 === 0,
);

The DOM is exported as dom, because the XPath side declares Document, Element and Node as structural types while the DOM side implements them:

import { dom } from '@push.rocks/smartxml/xpath';

const document = new dom.Document();

The engine and the DOM are forks kept in this repository rather than dependencies, so corrections to XPath semantics are made here and ship with the package. Their origin, licenses and the modifications made are recorded in third-party-notices.md.

Numbers behave the way XPath specifies rather than the way JavaScript does: xs:decimal is computed on its decimal digits, so 0.1 + 0.2 = 0.3 holds, and an xs:integer outside the safe range of a double keeps every digit, so a checksum over a 24 digit number is exact.

evaluateXPathToBoolean('0.1 + 0.2 = 0.3'); // true
evaluateXPathToString('string(xs:integer("830993497117024304") + 1)'); // '830993497117024305'
evaluateXPathToString('string(xs:integer("183988374829384736283847") mod 97)'); // '27', the step an IBAN check needs

The engine is measured against the part of the W3C QT3 test suite that covers arithmetic, casting and serialization: pnpm test runs 5,773 of its cases, error codes included, and the 148 it does not satisfy are listed with their reason in test/fixtures/qt3/known-gaps.json. The larger ones are xs:float (held as a double, so it is not 32 bit), durations in fn:sum, fn:avg, fn:min and fn:max, and casting to xs:QName. That file is a closed set: a new failure, a gap that starts passing and a gap that stops being reached all break the test. Measuring against W3C test material is not a conformance claim.

Schematron validation

@push.rocks/smartxml/schematron validates a document against ISO Schematron rules. Schematron states the conditions a document must satisfy as XPath expressions, which a grammar such as XSD cannot express. The rules are interpreted on the XPath engine above; no XSLT processor is involved.

import { Schematron, toSvrl } from '@push.rocks/smartxml/schematron';

const schema = Schematron.fromString(schemaXml);
const report = schema.validate(instanceXml);

report.valid;        // false when an assert failed or an expression could not be evaluated
report.failures;     // id, flag, message, location and the test that fired
report.engineErrors; // expressions the engine refused, never counted as a pass
toSvrl(report);      // the report in SVRL, for other Schematron tooling

Schemas that are bound to XSLT may declare helper functions inside the schema, which the European e-invoicing rule sets use for check digits. Those functions are compiled and registered with the engine, so no XSLT is needed to run them. sch:include, abstract patterns, phases, sch:let and sch:value-of in messages are supported; a rule context is treated as a location path.

An expression the engine cannot evaluate is reported rather than skipped: a validator that could not check a rule has not proven anything about the document.

Conclusion

The @push.rocks/smartxml package offers a straightforward and powerful means to work with XML in your JavaScript or TypeScript projects. By integrating it, you can easily convert between XML strings and JavaScript objects, allowing for efficient data processing and transmission in scenarios where XML is the preferred format. Whether you're building web services, APIs, or need to handle configuration files in XML, SmartXml offers the necessary tools to get the job done with minimal hassle.

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
A package for creating and parsing XML formatted files.
Readme
1.4 MiB
Languages
TypeScript 100%