XML to HTML Table
Converts a user inputed XML table to an plain HTML table
by Anov Siradj
HTML
<input type="file" id="fileinput" />
<table border="1px" id="t1"></table>
JavaScript
//this first block gets file input and saves it as a string to contents
function readSingleFile(evt) {
alert("yo");
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.readAsText(f);
r.onload = function (e) {
var contents = e.target.result;
//splits the string 'contents' into rows corresponding to table rows, saves as array 'lines'
var lines = contents.replace(/<Row|<PageSetup>/gm, "UNIQUE_EXPRESSION<Row");
lines = lines.split("UNIQUE_EXPRESSION");
//splits each line into individual cells, saves as 2D array 'Cells'
var Cells = [];
for (var j = 1; lines[j - 1].indexOf("</Table>") < 1; j++) {
lines[j] = lines[j].replace(/<Cell/gm, "UNIQUE_EXPRESSION2<Cell");
Cells[j - 1] = lines[j].split("UNIQUE_EXPRESSION2");
}
//Strips all other XML so each cell only contains the data we want
for (var x = 0; x < Cells.length; x++) {
for (var y = 0; y < Cells[x].length; y++) {
Cells[x][y] = Cells[x][y].replace(/<.*?>/gm, "");
}
}
//creates the HTML table using DOM HTML creation
var $table = $('#t1');
var $row; // = $('<tr>');
for (var a = 0; a < Cells.length; a++) {
$row = $('<tr>');
row = document.createElement("tr");
for (var b = 1; b < Cells[a].length; b++) {
var $cell = $('<td>');
$cell.append(Cells[a][b]).append("</td>");
$cell.clone().appendTo($row);
}
$row.append('</tr>');
$row.clone().appendTo($table);
}
};
} else {
alert("Failed to load file ");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);