NeedHate NeedHate - 6 months ago 25
HTML Question

Get data from XML file on page load

Its my first experience with xml, so obvious things are not so. I have a file in xml, and I need to retrieve data from it with javascript. The content of the file is following:

<?xml version="1.0" encoding="utf-8"?>
<Price><![CDATA[50 $]]></Price>

And I have to retrieve the data from it to my html page on load.
So the question is: how can I get 50$ and More Information texts from xml?


You can use XMLHttpRequest(), DOMParser(), for loop, recursion to iterate all nodes within xml document, check if .nodeType of node is 4, use .textContent property of CDATASection to retrieve text content of node

<!DOCTYPE html>
      function iterateNodes(nodes) {
        for (var i = 0; i < nodes.length; i++) {
          if (nodes[i].nodeType === 4) {
            document.body.innerHTML += nodes[i].textContent + "<br>"
            if (nodes[i].childNodes.length) {
      window.addEventListener("load", function() {           
        var request = new XMLHttpRequest();
        request.addEventListener("load", function() {
          var parser = new DOMParser(); 
          var xml = parser.parseFromString( this.response, "text/xml" )
          var nodes = xml.documentElement.childNodes;
        });"GET", "data.xml");