Javascript - XML / DOM

Environment

Browser

A browser has already a dom implementation with the webapi DOMParser

Node

There is no native DOM library.

Jsdom

jsdom - it runs only on node as it's dependent on the node module path, fs, ….

React-Native

See library (not jsdom)

Library

xmldom

A implementation of the DOMparser web api in pure javascript xmldom

let xml = `
<address>
  <distance>0.04</distance>
</address>
`
const doc = new DOMParser().parseFromString(xml, 'text/xml');
let distanceValue = doc.documentElement.getElementsByTagName("distance")[0]?.textContent;

2021-10-19 - querySelector and querySelectorAll are not yet part of the document interface of Xmldom

fast-xml-parser

From Xml to Json, Json to Xml with fast-xml-parser

Example

let xml = `
<address>
  <distance>0.04</distance>
</address>
`
const jsonObj = parser.parse(xml);
let distanceValue = jsonObj.address.distance;

htmlparser2

https://github.com/fb55/htmlparser2 - see also cheerio if you want selection

import {parseDocument, ElementType} from 'htmlparser2';

let xml = `
<address>
  <distance>0.04</distance>
</address>
`
const document = parseDocument();
return document.children.map(node => {
   switch (node.type) {
      case ElementType.Text:
        console.log("Text node");
        break;
      case ElementType.Tag:
        console.log("Tag node");
        break;
    }
});

Cheerio

Cheerio is based on htmlparser2 and implements a Jquery like interface for non-browser environment.

https://cheerio.js.org/

Support

jsdom on react native - path could not be found within the project

If you try to use jsdom as dom engine on a react-native project, you would get the below error message (that comes from Metro Bundler)

Unable to resolve module path from node_modules\jsdom\lib\api.js: path could not be found within the project.

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  1 | "use strict";
> 2 | const path = require("path");
    |                       ^
  3 | const fs = require("fs").promises;
  4 | const vm = require("vm");
  5 | const toughCookie = require("tough-cookie");

You get this message because jsdom depedent on the node module such as :

  • path
  • fs

etc …

You can't use jsdom on react native.







Share this page:
Follow us:
Task Runner