简体   繁体   中英

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"?>
<data>
    <Texts>
        <Price><![CDATA[50 $]]></Price>
        <CTA_text><![CDATA[MORE INFORMATION]]></CTA_text>
    </Texts>
</data>

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?

Try to use the javascript XML parser. It's pretty easy. Here is an examle: http://www.w3schools.com/xml/dom_intro.asp

<script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            myFunction(xhttp);
        }
    };
    xhttp.open("GET", "books.xml", true);
    xhttp.send();

    function myFunction(xml) {
        var xmlDoc = xml.responseXML;
        document.getElementById("demo").innerHTML =
        xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
    }
</script>

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>
<html>    
  <head>
    <script>
      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) {
              iterateNodes(nodes[i].childNodes)
            }
          }
      }
      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;
          iterateNodes(nodes)              
        });
        request.open("GET", "data.xml");
        request.send();
      })
    </script>
  </head>    
  <body>      
  </body>    
</html>

plnkr http://plnkr.co/edit/gEZCWeHTwzk7o1GSAqzJ?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM