Friday, 15 June 2012

HTML table to XML in JavaScript


Please note this code will now be hosted github :

https://github.com/aetuk/wasjsapi/blob/master/tabletoxml.js

getCheckedRowsXml = function(htmltablename, xmltablename) {
var rowsIndex;
var xmltable = '';
var xmlrow = '';
var rows = document.getElementById(htmltablename).getElementsByTagName(
'tbody')[0].getElementsByTagName('tr');
for (i = 1; i < rows.length; i++) {

// Xml defined based on a ‘checked’ checkbox - Feel free to add your
// criteria here to filter the data selected ( or not)
if (rows[i].getElementsByTagName('td')[0]
.getElementsByTagName('input')[0].checked) {
// here "i" is the row number if checked

var cells = rows[i].getElementsByTagName('td');
for (c = 0; c < cells.length; c++) {
// xmlrow = xmlrow + '
// '+cells[c].id+'="'+cells[c].innerHTML+'"';
xmlrow = xmlrow + '<' + cells[c].id + '>'
+ cells[c].innerHTML + '</' + cells[c].id + '>';
}
if (xmlrow != null)
xmltable = xmltable + '<row>' + xmlrow + '</row>';
xmlrow = '';
}
}
if (xmltable != null)
xmltable = '<' + xmltablename + '>' + xmltable + '</'
+ xmltablename + '>';
return (xmltable);
}

This function will return a xml representation of a HTML table for each  row on the table has a checkbox set to true in the form : <xmltablename><row><cell_name>cell_value<cell_name/><row/><xmltablename/>

It assumes that the html table has a checkbox on each row and that the name of the column is defined by cell id. Feel free customise it to suit your needs.