简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM