I saw that in some xml files, child numbers are not the same for the elements which will correspond to our table rows. So i created a more smart version which is error tolerant.
xml to html table v.2
// JScript File
function ConvertToTable(targetNode)
{
// if the targetNode is xmlDocument this line must be uncommented
// targetNode = targetNode.childNodes[0];
// first we need to create headers
var rowCount = targetNode.childNodes.length
// name for the table
var columnList = GetColumnList();
var myTable = document.createElement("table");
myTable.className ="general";
var firstRow = myTable.insertRow();
var firstCell = firstRow.insertCell();
firstCell.colSpan = columnList.length;
firstCell.innerHTML = targetNode.nodeName;
// name for the columns
var secondRow = myTable.insertRow();
for(var i=0;i<columnList.length;i++)
{
var newCell = secondRow.insertCell();
newCell.innerHTML = targetNode.childNodes[0].childNodes[i].nodeName;
}
// now fill the rows with data
for(var i2=0;i2<rowCount;i2++)
{
var newRow = myTable.insertRow();
for(var j=0;j<columnList.length;j++)
{
var newCell = newRow.insertCell();
newCell.innerHTML = GetColumnValue(i2,columnList[j]);
}
}
function GetColumnValue(rowIndex,columnName)
{
var columnValue ="";
for(var i=0; i<targetNode.childNodes[rowIndex].childNodes.length; i++)
{
if(targetNode.childNodes[rowIndex].childNodes[i].nodeName == columnName)
columnValue = targetNode.childNodes[rowIndex].childNodes[i].firstChild.nodeValue;
}
return columnValue;
}
function GetColumnList()
{
var columnNames = new Array();
var rowIndexToGetNames = 0;
var _columnCount = 0;
for(var i2=0;i2<rowCount;i2++)
{
if(targetNode.childNodes[i2].childNodes.length > _columnCount)
{
_columnCount = targetNode.childNodes[i2].childNodes.length;
rowIndexToGetNames = i2;
}
}
var selectedRow = targetNode.childNodes[rowIndexToGetNames];
for(var i=0; i< selectedRow.childNodes.length; i++)
{
columnNames.push(selectedRow.childNodes[i].nodeName);
}
return columnNames;
}
// i prefer to send it as string instead of a table object
return myTable.outerHTML;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.