javascriptxmlexpressaxiosxml2js

Trouble getting XML file values w/ JS


I need to pass some items from an XML file, as parameters to the res.renderer() function (shown further below) . I currently can achieve this with this sample XML:

Sample.xml

 <breakfast_menu>
   <food>
     <name>Belgian Waffles</name>
    </food>
   <food>
     <name>Strawberry Belgian Waffles</name>
   </food>

...using this code:

 const parseString = require('xml2js').parseString;
 const axios = require('axios');

let url = 'https://www.w3schools.com/xml/simple.xml';
app.get('/dynamic_view', function(req, res, next){

     //GET THE XML URL
     axios.get(url)

       //PARSE THE XML FILE
       .then(({ data }) => {
         parseString(data, (err, { breakfast_menu: { food } }) => {
           if (err) return next(err)
           
           let food_names = [];
           //ITERATE OVER NAME VALUES OF FOODS, PUSH THEM TO AN ARRAY
           food.map(({name}) => {
             console.log(name);
             food_names.push(name[0]);
           });

           //PASS THE ARRAY WITH VALUES TO res.renderer()
           res.render('dynamic', {
              names: food_names
           });
         });        
       })
  })

However, I'm having trouble navigating and passing values from another XML that has more sub-elements:

Problem.xml

<rss xmlns="https://url/rss" version="5.0">
    <channel>
          <description>Main channel</description>
          <link/>

          <product>
          <id>4bc1d0ac9276</id>
          <description></description>
          </product>

           <product>
          <id>4bc1d0ac9276</id>
          <description></description>
          </product>

    </channel>
</rss>

How can I access the 'product' elements of my problem XML file, push them to array and pass it to the res.renderer, the same way as shown in the working code snippet w/ Sample.xml file? I'm having trouble navigating the XML structure of Problem.xml with JS.

Been stuggling with this for a while and Any help is appreciated!


Solution

  • Here's how I solved it:

    parseString(data, (err, file) => {
                if (err) return next(err)
                title=file.rss.channel[0].item;