Home > Mobile >  How to parse XML files using XPath with ESM in Node.js
How to parse XML files using XPath with ESM in Node.js

Time:09-21

I am working on a task for work that involves using an XML file and needing to parse that file with XPath using .mjs files. I don't normally code using .mjs files and the data that I am typically working with is JSON. This is a legacy app that we are converting from C# to Node and we need to be able to parse XML files. The requirements are as follows:

Must use .mjs extension Module must run in Node.js so it should not depend on any browser-specific JavaScript features Module's default export should be an asynchronous function which crawls the directory tree and parses the XML files it finds

I am at a loss for even where to begin. Any assistance with pointing me in the right direction would be extremely helpful. Thank you in advance.

CodePudding user response:

To give you a very simple example using XPath 3.1 with SaxonJS in an ESM module:

import { default as SaxonJS } from 'saxon-js';

const xml = `<root>
  <item>a</item>
  <item>b</item>
  <item>c</item>
</root>`;

const xmlDoc = await SaxonJS.getResource({ type: 'xml', text: xml });

console.log(SaxonJS.XPath.evaluate(`random-number-generator(current-dateTime())?permute(/root/item) => serialize(map { 'method' : 'xml', 'indent' : true() })`, xmlDoc));

Documentation is at https://www.saxonica.com/saxon-js/documentation2/index.html

  • Related