简体   繁体   中英

link my XML file to my HTML page

I need some help on JavaScript, I have created a XML file I would like for it to be displayed in my HTML page that I also created.I would like this to be displayed on the browser in the following manner inside a Div element with the help of JavaScript :


items
   |
   |__fruits
   |    |_____orange
   |    |_____Banana
   |    |_____Mango
   |
   |__drinks  

<?xml version="1.0" encoding="utf-8"?>
<items image="images/items.JPG">
  <fruits image="images/fruits.JPG">
    <orange  image="images/orange.JPG" qty="15" rate="Rs 40/kg"/>
    <banana  image="images/banana.JPG" qty="25" rate="Rs 20/kg"/>
    <mango  image="images/mango.JPG" qty="19" rate="Rs 45/kg"/>
  </fruits>
  <drinks  image="images/drinks.jpg">
    <pepsi image="images/pepsi.jpg" qty="10" rate="Rs 22/litre"/>
    <coke image="images/coke.jpg" qty="8" rate="Rs 21/litre"/>
    <wines image="images/wines.JPG">
      <grapes  image="images/grapes.JPG" qty="4" rate="Rs 60/litre"/>
      <apple  image="images/apple.JPG" qty="2" rate="Rs 80/litre"/>
    </wines>
    <harddrinks image="images/harddrinks.JPG">
      <whisky  image="images/whisky.JPG" qty="3" rate="Rs 100/litre"/>
      <beer  image="images/beer.JPG" qty="3" rate="Rs 30/litre"/>
    </harddrinks>
  </drinks>
</items>

You'll have to parse through the XML file to suit your specific needs, but maybe start by loading in the xml file:

var xmlDoc;
<!--
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  } 
else // Internet Explorer 5/6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET","PathToYourXMLFilename.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;

Then place each node element into an array (or several):

var myFruits=xmlDoc.getElementsByTagName("fruits");

Can i get more simpler method to browse through all the node

    var xmlDoc = loadXMLDoc('data.xml');
var myItems = xmlDoc.getElementsByTagName("items");
var outputDiv = document.getElementById("dvList1");

var divOutput = document.createElement("div");
var divstr = document.createTextNode(xmlDoc.documentElement.nodeName);
divOutput.appendChild(divstr);
outputDiv.appendChild(divOutput);

x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{ 
if (x[i].nodeType==1)
  {//Process only element nodes (type 1) 
  var divOutput = document.createElement("div");
  var divstr = document.createTextNode(x[i].nodeName);
  divOutput.appendChild(divstr);
  outputDiv.appendChild(divOutput);
  } 
}

I want to get output something like the following

items
   |
   |__fruits
   |    |_____orange
   |    |_____Banana
   |    |_____Mango
   |
   |__drinks  

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