-1

I want to use javascript to get information from a xml file loaded into a webpage.

The below given is the xmlfile(a.xml) i am using.

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 want to access nodes under a specific node in xml using java script? That is i want to access Time node after i access step node. And the below given is the index.html page to which i want 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)               // REQUEST COMPLETED.
      showTheList(this.responseXML);      // ALL SET. NOW SHOW XML DATA.
  }

  oXHR.onreadystatechange = reportStatus;
  oXHR.open("GET", "a.xml", true);      // true = ASYNCHRONOUS REQUEST 
                                   //(DESIRABLE), false = SYNCHRONOUS REQUEST.
  oXHR.send();

  function showTheList(xml) {
    var divBooks = document.getElementById('books');        // THE PARENT DIV.
    var Book_List = xml.getElementsByTagName('Step');       // THE XML TAG NAME.
    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 above code I am trying to access the Time subnode under the step node. and I have used arrays in the above example as the xml page i am using have lots of Step subnodes , and i want to access the Time subnodes under Step for each one of them.

thanks, Any help is appreciated

6
  • This is my first post in stack over flow.. sorry for any missing informations Commented Jul 5, 2018 at 21:01
  • Add some sourcecode. What have you tried? Commented Jul 5, 2018 at 22:39
  • 1
    @AlfonsoNishikawa, i have updated my post, please have a look at it. Commented Jul 6, 2018 at 16:04
  • Thank you, @NIMALKRISHNA . An improvement: use indentation in your sourcecode. Commented Jul 7, 2018 at 11:59
  • i have posted a new question , please have a look at it ,thanks Commented Jul 9, 2018 at 17:32

1 Answer 1

2

You have the option of iterating over the xml nodes directly, employing one of the XPath processing APIs. It basically suffices to rewrite your showTheList function. What follows is a complete standalone solution, however:

<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 may beunnecessary depending on the ajax lib used. 
            let parser = new DOMParser();
            let xmlDoc = parser.parseFromString(s_xmlsource, "application/xml");

            // Obtain the xml node set containing the needed info.
            // In this case, these are 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>

Code has been tested.

Note

The sample xml provided in the question is not well-formed since it lacksa unique root element. The solution would still work but only consider the first Stepelement.

Update

To allow for 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 whatever else
    oXHR.send();
} // getData

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

<body onLoad="getData()">
Sign up to request clarification or add additional context in comments.

4 Comments

Hi collapsar, thanks for the help. I tried the above function but it is not displaying the time value. checking what went wrong now.. :(
@NIMALKRISHNA Your xml sample lacks a unique root element, which basically blots out allbut the first Step elements. I introduced an artificial Steps element in the revised solution. The solution works as-is. Note that I have also changed the time stamp in the second Time element to disambiguate the output.
Hi @collapsar , is there a way to add this xml file as a seperate file instead of puting it in html ?because i need to display the informations from an xml file which keeps on changing.
@Nimalkrishna I've complemented the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.