node.jsxmljsdom

Target an xml node in node js


I am very new to NodeJS and would request the readers to please be kind if my query is too basic.

I have an xml file that was easy to parse and target certain nodes with DOMParser and querySelector with javascript for the frontend (browser)... but I was trying the same on the backed with node and I realised that DOMParser is not really a part of the backend.. Here's what I am trying..

fetch(`http://localhost:3000/data/rogan/gallery.xml`)
    .then((response) => response.text())
    .then((xml) => {
      const xmlDOM = new JSDOM(xml, {
        contentType: "text/xml",
        features: {
          QuerySelector: true,
        },
      });

      const images = xmlDOM.querySelector("img");
      console.log(images);
      res.send(images);
    })
    .catch((err) => console.log(err));
});

Is the use of querySelector wrong in node? I mean is that a front-end thing and not something we use in node?

I am able to get the XML but I am not sure how to target some specific nodes in the xml that I want to push to an array or an object (I haven't yet reached that stage but first I need to target the nodes)..

Any help/advise would be appreciated.


Solution

  • It looks like you call the querySelector in the wrong way. Here is what I found on the documentation of JSdom:

    dom.window.document.querySelector("p").textContent
    

    In your case, I should be

    xmlDOM.window.document.querySelector("img");