...

View Full Version : JavaScript and the XML DOM



ChuckSchuldiner
02-16-2005, 11:34 AM
what i am trying to do is by using javascript i am trying to create a table using the information in a xml file ... i have truncated the javascript code to show only the part that i would use to create the header for the table...

the html code....

<html>

<head>
<Script type="text/javascript">

var IE=(navigator.appName.indexOf("Explorer")>-1);

if(IE)
{

var xmlDoc=new ActiveXObject("MICROSOFT.XMLDOM");
xmlDoc.async=false;
}
else
{
var xmlDoc=document.implementation.createDocument("","doc",null);
}

xmlDoc.load("xml1.xml");

function xmlTable()
{

var papaNode=xmlDoc.getElementsByTagName("child");

//The Table

var tableElement=document.createElement("TABLE");
var tableRow=document.createElement("TR");

//Table Header

for(i=0;i<papaNode[0].childNodes.length;i++)
{

if(papaNode[0].childNodes[i].nodeType!=1)continue;

var tableCell=document.createElement("TH");
var theText=document.createTextNode(papaNode[0].childNodes[i].nodeName);
tableCell.appendChild(theText);
tableRow.appendChild(tableCell);

}

tableElement.appendChild(tableRow);
document.getElementById("p1").appendChild(tableElement);


}

</script>
</head>

<body>

<a href="javascript:xmlTable()">xml table</a>
<br>
<p id="p1"></p>

</body>
</html>

and the XML file(xml1.xml) is...

<?xml version="1.0" encoding="ISO-8859-1"?>

<group>
<child>
<name>Glen Benton</name>
<age>13</age>
<class>1B</class>
</child>
<child>
<name>Sean Reinhardt</name>
<age>12</age>
<class>1B</class>
</child>
<child>
<name>Angel Ripper</name>
<age>14</age>
<class>2C</class>
</child>
</group>


the problem with the above code is that ... when i click on the link "xml table" no data is displayed in the page ... where could i have gone wrong
the header part of the table should look like this...

+--------------------------+
| name | age | class |
+--------------------------+

Kor
02-17-2005, 02:20 PM
I guess that you must have insert the row's append method inside the loop, not outside


...
var tableElement=document.createElement("TABLE");
for(i=0;i<papaNode[0].childNodes.length;i++)
{
if(papaNode[0].childNodes[i].nodeType!=1)continue;
var tableRow=document.createElement("TR");
var tableCell=document.createElement("TH");
var theText=document.createTextNode(papaNode[0].childNodes[i].nodeName);
tableCell.appendChild(theText);
tableRow.appendChild(tableCell);
tableElement.appendChild(tableRow);
}
document.getElementById("p1").appendChild(tableElement);
...

Kor
02-17-2005, 02:44 PM
eer, I have notice that TBODY element is missing also....



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum