JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage.

Below is the XML file (a.xml) that I am working with.

a.xml

<?xml version="1.0"?>

<Step rID="T6">
  <Obj ><![CDATA[Get Data Table - Passed]]></Obj>
  <Details ><![CDATA[]]></Details>
  <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
  <TimeTick>1530810986</TimeTick>
  <NodeArgs eType="User" icon="5" nRep="9" >
    <Disp><![CDATA[Get Data Table - Passed]]></Disp>
  </NodeArgs>
</Step>
<Step rID="T7">
  <Obj ><![CDATA[GetDataTable - Successful]]></Obj>
  <Details ><![CDATA[Toral Row get:65534]]></Details>
  <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
  <TimeTick>1530810986</TimeTick>
  <NodeArgs eType="User" icon="5" nRep="10" status="Passed" >
    <Disp><![CDATA[GetDataTable - Successful]]></Disp>
  </NodeArgs>
</Step>

I am interested in accessing specific nodes within the XML using javascript. In particular, I want to access the Time node after accessing the Step node.

Below is the index.html page where I intend to load the XML data:

index.html

<html>
  <head>
    <title>Report</title>
    <style></style>
  </head>
  <body>
    <p>Results of  <b>Test cases</b> </p>
    <div id="books"></div>
  </body>

  <script>
  var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  var testcase_Number = 0;
  var endOfTest= 0;
  function reportStatus() {
    if (oXHR.readyState == 4)               
      showTheList(this.responseXML);      
  }

  oXHR.onreadystatechange = reportStatus;
  oXHR.open("GET", "a.xml", true);      
  oXHR.send();

  function showTheList(xml) {
    var divBooks = document.getElementById('books');        
    var Book_List = xml.getElementsByTagName('Step');       

    var divLeft = document.createElement('div');
    divLeft.className = 'col1';

    for (var i = 0; i < Book_List.length; i++) {
      divLeft.innerHTML=Book_List[i].getChildElementsByTagName("Time")[0].nodeValue;
      divBooks.appendChild(divLeft);
    }
  };
  </script>
</html>

In the code above, the goal is to access the Time subnode under the Step node. Arrays are used as the XML file contains numerous Step subnodes, and I need to access the Time subnodes under each one of them.

Thank you for any assistance.

Answer №1

If you choose to iterate through the xml nodes directly, you can utilize one of the XPath processing APIs. Simply update your showTheList function. Alternatively, here is a complete stand-alone solution:

<html>
    <head>
    <title>Report</title>
    <style>

    </style>
    <script>
        function showTheList() {
            let x_xmlisland = document.getElementById("template_xml");
            let s_xmlsource = x_xmlisland.textContent; 

            // Parse xml. This step may be unnecessary depending on the ajax library used. 
            let parser = new DOMParser();
            let xmlDoc = parser.parseFromString(s_xmlsource, "application/xml");

            // Retrieve the xml node set containing the required information.
            // In this case, we are interested in the textual contents of all 'Time' elements that are children of a 'Step' node.
            let xpr_time  = xmlDoc.evaluate("//Step/Time/text()", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
            let node_time
              ;

            let divBooks = document.getElementById('books');        // THE PARENT DIV.
// debugger; // uncomment for tracing 
            while ( ( node_time = xpr_time.iterateNext() ) !== null ) { // iterate over xml nodes
                let divLeft = document.createElement('div');
                divLeft.className = 'col1';
                divLeft.innerHTML = node_time.textContent;  // The xpath expression references the 'text()' function which provides a text node. String must still be extracted. 
                divBooks.appendChild(divLeft);
            }
        }
        </script>
    </head>
    <body onLoad="showTheList()">
        <script type="text/xml" id="template_xml"><?xml version="1.0"?>
<Steps>
    <Step rID="T6">
        <Obj ><![CDATA[Get Data Table - Passed]]></Obj>
        <Details ><![CDATA[]]></Details>
        <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
        <TimeTick>1530810986</TimeTick>
        <NodeArgs eType="User" icon="5" nRep="9" >
            <Disp><![CDATA[Get Data Table - Passed]]></Disp>
        </NodeArgs>
    </Step>
    <Step rID="T7">
        <Obj ><![CDATA[GetDataTable - Successful]]></Obj>
        <Details ><![CDATA[Toral Row get:65534]]></Details>
        <Time><![CDATA[7/5/2018 - 13:16:27]]></Time>
        <TimeTick>1530810986</TimeTick>
        <NodeArgs eType="User" icon="5" nRep="10" status="Passed" >
            <Disp><![CDATA[GetDataTable - Successful]]></Disp>
        </NodeArgs>
    </Step>
</Steps>
        </script>
        <p>Results of  <b>Test cases</b> </p>
        <div id="books"></div>
    </body>
</html>

The code has been thoroughly tested.

Note

The sample xml provided in the question is not well-formed as it lacks a unique root element. Although the solution would work, it would only consider the first Step element.

Update

In order to handle xml from an external source, the ajax code needs to be reintroduced:

function getData() {
    let oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    oXHR.onreadystatechange = function() {
        if (oXHR.readyState == 4 && oXHR.status == 200) {
            showTheList(oXHR);
        }
    };
    oXHR.open("GET", "state_data.xml", true); // ...or any other source
    oXHR.send();
} // getData

Without local data, it no longer makes sense to register showTheList as an onLoad handler.

<body onLoad="getData()">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AJAX (Vanilla JavaScript): Sending Image through HTTP Request

I am a beginner with ajax and prefer not to use frameworks. I attempted to use PHP to determine if a file is set and display either true or false, but it didn't work as expected. I'm unsure of where I went wrong. Below is my HTML and JS code: & ...

Troubleshooting not locating view files in ExpressJS and implementing client-side JavaScript and CSS deployment in ExpressJS

My JavaScript file is located in the same directory as my HTML file, and I am trying to render it. I'm unsure of what I may be missing. How difficult could it possibly be? var express = require('express'); var app = express(); app.engine( ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

What are the available methods for incorporating node.js dependencies into a Python package?

At the moment, I am working with a few Python packages that are not yet published and are used locally. For development purposes, I install these packages on Linux using a Bash script into an activated virtual environment. Here's how I do it: cd /roo ...

Firefox does not support jQuery AJAX functionality, unlike Internet Explorer where it works smoothly

Can anyone help me figure out how to ensure that this code works smoothly on both IE and Firefox? The confirm prompts are functioning in Firefox, but the AJAX request isn't triggering. According to Firebug, there's an error at line 9631 of jquery ...

Is there a way to identify the duplicated input element values using jquery?

Just starting out in the world of web development and jQuery. I have an input element that has been bound with a blur event. Here's the code snippet: // Here are my input elements: <input class="input_name" value="bert" /> <input class="inp ...

Is there a way to locate the final element in a specific angular ng-repeat loop subset?

The final entry in the labels section may not be checked, making $last unsuitable for this scenario. This results in the following sequence: peaches, bananas, cherries, watermelon, How can I locate the last item in an angular ng-repeat loop while using an ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

Creating a Rest API URL in Vue.js by extracting form values

I just finished coding this Vue component: <template> <div> <h2>Search User By ID</h2> <input v-model="userId" type="number" placeholder="modify me" /> <br /> <p v-if="userId.length != 0"> ...

mongoose.js now prevents update methods from returning documents

Is it feasible to avoid fetching any data from the database after performing the SOME_MODEL.findOneAndUpdate() operation? I could potentially utilize the lean() and select() methods. However, all I really require is a callback confirming the successful up ...

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Issues with Pdf.js functionality on Internet Explorer

Could someone shed some light on why this code isn't functioning in Internet Explorer? It works perfectly fine in Chrome. Snippet of my HTML: <head> <script type='text/javascript' src="//code.jquery.com/jquery-1.9.1.js"></sc ...

Can we utilize conditions to both select and deselect items using JavaScript and PHP together?

I have a selection list with checkboxes that is dynamically generated based on certain conditions in the code snippet below. if ($data_inteiro_01 <= $data_inteiro_02) { if ($parcela[$i] === 0) { $display = 'disabled'; } } els ...

What is the best way to create a nullable object field in typescript?

Below is a function that is currently working fine: export const optionsFunc: Function = (token: string) => { const options = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, } ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

Protecting a javascript string in php: A comprehensive guide

Having trouble with my PHP javascript string. Attempted to add a string to a variable within a switch statement but encountered an error: $blocPub = '<script type="text/javascript"> var rdads=new String(Math.random()).substring (2, 11 ...

Styling for the DataTable disappears upon loading jQuery

my PHP file named "zero3data.php" <?php printf('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">'); printf('<thead>'); printf('<tr>'); ...