user3472065
user3472065

Reputation: 1389

Display XML Data in an HTML Page

I need to display the data stored in an XML file in my HTML page.

I wrote this code (my_data.html):

<html>
<body>

<script>
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
xmlhttp.open("GET","my.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 

document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("zzz");
for (i=0;i<x.length;i++)
 { 
  document.write("<tr><td>");
  document.write(x[i].getElementsByTagName("data2")[0].childNodes[0].nodeValue);
  document.write("</td><td>");
  document.write(x[i].getElementsByTagName("data3")[0].childNodes[0].nodeValue);
  document.write("</td></tr>");
 }
document.write("</table>");
</script>

</body>
</html>

The XML has this structure and it is in the same folder of the html page:

<xxx>
    <yyy>
        <zzz>
            <data1>AAA</data1>
            <data2>000</data2>
            <data3>BBB</data3>
            <data1>CCC</data1>
            <data2>111</data2>
            <data3>RRR</data3>
        </zzz>
        <zzz>
            <data1>YYY</data1>
            <data2>555</data2>
            <data3>OOO</data3>
            <data1>PPP</data1>
            <data2>444</data2>
            <data3>LLL</data3>
        </zzz>
    </yyy>
</xxx>

When I launch the html page, nothing is displayed.

Upvotes: 3

Views: 171

Answers (1)

Syed Shoaib Abidi
Syed Shoaib Abidi

Reputation: 2366

You need to create a server for this purpose as you would get this error always Cross origin requests are only supported for HTTP . You can install XAMPP or WAMP for this purpose and try again.

Upvotes: 1

Related Questions