xml loop through nodes and then print out using Node js

62 views Asked by At

I am trying to loop through the XML nodes in js using user input eg. if I entered "unit" then everything within the unit tag should print out in the output

<course>
     <name>...</name>
     <duration>...</duration>
     <unit>
          <title>...</title>
          <lecturer>
              <surname language="English">...</surname>
              <othernames language="English">...</othernames>
              <email>...</email>
          </lecturer>
     </unit>
</course>

currently, I am able to get the title in unit tag but unable to get the lecturer, surname, othernames and email tag to print out. What can I use to get the the lecturer, surname, othernames and email tag to print out?

const xmldom = require('xmldom').DOMParser;
const fs = require('fs');
const readLineSync = require('readline-sync');

let parser, doc, targetNodes;
let i, count = 0, userInput;
let targetObj, fcObj, parentObj;

// use fs to read xml document
fs.readFile('course.xml', 'utf-8', function (err, data) {
    if (err) {
        throw err;
    }
    // construct parser
    parser = new xmldom();
    // call method to parse document - not the type
    doc = parser.parseFromString(data, 'application/xml');

    userInput = readLineSync.question("Enter tag to be printed: ");

    // use DOM Node method
    targetNodes = doc.getElementsByTagName(userInput.toLowerCase());
    console.log("Tag " + userInput + " entered");
    
    for (i in targetNodes) {
        // process current ith node
        targetObj = targetNodes[i];
    
        // if it is the firstchild
        if (targetObj.firstChild) {
            // obtain the node value
            fcObj = targetObj.childNodes;
            parentObj = targetObj.parentNode;
            
            if (parentObj == null && count == 0){
                console.log("No identical tag found.");
            } else {
                count = 1;
                if (parentObj != null) {
                    if (fcObj[count].childNodes) {
                        console.log(fcObj[count].childNodes[0].nodeValue);
                    } else {
                        console.log(fcObj[count].nodeValue);
                    }
                }
            }
        }
    }
});
0

There are 0 answers