Converting Table data to the xml structured data - javascript

I stuck the below requirement, Here I have to show all the table data to the xml structured data, I tried with the following, I'm getting xml structure but struggling to show row data with table headers like below
<rowset>
<row name='SequnceNumber'>
<row>Item</row>
<row>Weight</row>
<row>LableNo</row>
<row>Unitcost</row>
<row>Delete</row>
</rowset>
<rowset>
<rowset name='1212121'>
<Item>test1</Item>
<Weight>3000</Weight>
<LableNo>test1</LableNo>
<Unitcost>test1</Unitcost>
<Delete>test1</Delete>
</rowset>
I tried with below code,
$(document).ready(function(){
$("#idXmlData").click(function(){
var xmlStart = "<?xml version=\"1.0\" encoding=\"UTF-8\">";
var xml = xmlStart;
$(".mutliple tr").each(function() {
var cells = $("td", this);
if (cells.length > 0) {
xml +="<rowset name='" + cells.eq(0).text() + "'>\n";
for (var i = 1; i < cells.length; ++i) {
//var tableHeaders=["SequnceNumber","Item","Weight","LableNo","Unitcost","Delete"];
//for(var j=0;j<tableHeaders.length;j++){
// xml += "\t<"+j+">" + cells.eq(i).text() + "</"+j+">\n";
xml += "\t<row>" + cells.eq(i).text() + "</row>\n";
//}
}
xml += "</rowset>\n";
}
});
window.alert(xml);
});
});
JS fiddle

It will be a bit easier if you format your table to include header with th as you can see in the following code, because separating header text from other rows is going to make things a bit simpler.
Here's JS for that :
$("#idXmlData").click(function(){
var xmlStart = "<?xml version=\"1.0\" encoding=\"UTF-8\">";
var xml = xmlStart;
var xmlFirstRowSet = "<rowset><row name='";
var thArray = new Array();
$('th').each( function(index) {
thArray[index] = $(this).html();
});
xmlFirstRowSet = xmlFirstRowSet + thArray[0] + "'>";
var headerRowSet='';
for(var i=1; i< thArray.length; i++) {
headerRowSet = headerRowSet + "<row>" + thArray[i] + "</row>";
}
headerRowSet = headerRowSet + "</rowset>";
xmlFirstRowSet = xmlFirstRowSet + headerRowSet;
var bodyRowSet ='';
$(".mutliple tbody tr").each(function() {
bodyRowSet = bodyRowSet + "<rowset name='" + $(this).find('td').html() + "'>";
$(this).find('td:not(:first-child)').each(function() {
$td = $(this);
var tdValue = $(this).html();
var $th = $td.closest('table').find('th').eq($td.index()).html();
bodyRowSet = bodyRowSet + "<" + $th + ">" + tdValue + "</" + $th + ">";
});
bodyRowSet = bodyRowSet + "</rowset>";
});
xml = xmlStart + xmlFirstRowSet + bodyRowSet;
console.log(xml);
window.alert(xml);
});
Here's a working Fiddle

Related

Select one Particular sheet instead of listing all the sheets. Google app script, Code

I got this code from here : Display Spreadsheet Data to HTML Table
thanks to the great work of Cooper.
function htmlSpreadsheet(ssO) {
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(ssO.id);
var sht=ss.getSheetByName(ssO.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
s+='</body></html>';
var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
var opO={hl:s,name:namehl,shname:shnamehl};
return opO;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.openById(updObj.id);
var sht=ss.getSheetByName(updObj.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet() {
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
//working on this function right now 2017/11/08
function getAllSheets(ssO) {
var ss=SpreadsheetApp.openById(ssO.id);
var allSheets=ss.getSheets();
var vA=[['Select Sheet']];
for(var i=0;i<allSheets.length;i++)
{
var name=allSheets[i].getName();
vA.push([name]);
}
return {array:vA,type:'sel2'};
}
What I am trying to do is on a Single sheet. That is I don't want to browse all sheets and select among them~
I have tried modifying this code
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
// var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
// var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
I have used sheet Id instead of file.getId(), But It just don't work.
Please help me.
Change:
var files = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS)
To getFileById():
var file = DriveApp.getFileById("sheet Id");
Then remove the loop:
function getSingleSpreadSheet() {
var file = DriveApp.getFileById("sheet Id")
var fileName = file.getName()
var fileId = file.getId()
var vA = []
vA.push([fileName, fileId])
return {
array: vA,
type:'sel1'
}
}

how to display image through XML to html

Hie i am practicing XML , Javascript. I want to display image for each animal in a row. But my main problem arises uneven nesting in images . Some have two images while some have 4. I have XML File as follows:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
My javascript for img is :
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
Try this. This get's the document node of xml and queries for images from it. Once you have the array, you iterate over it and get the inner text from the node.
var xmlimages = xml.getElementsByTagName('image');
for(var i=0; i< xmlimages.length; i++) {
images.src = "images/" + xmlimages[i].innerHTML.trim(); // trim used to remove all the white space from text that you get when you use innerHTML
}
Please insert loop on node:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}
Try to get Animal as an object, then create a HTMLstring and insert it in node;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
or you can define animal array more functional way =)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
I didn't test it, but it should work.

Filter xml file using Javascript

I am trying to rebuild an old application without the loss of data. The current data has all been stored in xml files that i am trying to read using Javascript.
This is the Javascript (i'm new to this, feedback is appreciated):
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "writers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
for (var i = 0; i < Customers.children.length; i++){
var Customer = Customers.children[i];
//Create div's for data
document.getElementById("body").innerHTML += "<div id='who" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='age" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='hobby" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='image" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='something" + i + "'></div>"
//Assign data to correct divs
var who = Customer.getElementsByTagName("name");
var who2 = who[0].textContent.toString();
document.getElementById("who"+i).innerHTML += who2;
var age = Customer.getElementsByTagName("age");
var age2 = age[0].textContent.toString();
document.getElementById("age"+i).innerHTML += age2;
var hobby = Customer.getElementsByTagName("hobby");
var hobby2 = hobby[0].textContent.toString();
document.getElementById("hobby"+i).innerHTML += hobby2;
var image = Customer.getElementsByTagName("image");
var image2 = image[0].textContent.toString();
document.getElementById("image"+i).innerHTML += image2;
var something = Customer.getElementsByTagName("something");
var something2 = something[0].textContent.toString();
document.getElementById("something"+i).innerHTML += something2;
}
This is an example of my xml file:
<doc>
<person>
<name>Paul</name>
<age>21</age>
<hobby>blabla</hobby>
<image>thisisanimage.jpg</image>
<something>Random string</something>
</person>
<person>
<name>Peter</name>
<age></age>
<hobby>blabla</hobby>
<image>thisisanimage.jpg</image>
<something>Random string</something>
</person>
</doc>
Now i am trying to filter Peter out, because the age field is empty. Anyone got an idea?
The easiest way is to add a condition in the loop, to test if the age is blank. If the age value is blank then the if block will not be entered, and the next iteration of the loop will start.
for (var i = 0; i < Customers.children.length; i++) {
var Customer = Customers.children[i];
var age = Customer.getElementsByTagName("age");
var age2 = age[0].textContent.toString();
if (age2 != '') { // only do the below code if age2 is not blank
//Create div's for data
document.getElementById("body").innerHTML += "<div id='who" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='age" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='hobby" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='image" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='something" + i + "'></div>"
document.getElementById("age" + i).innerHTML += age2;
//Assign data to correct divs
var who = Customer.getElementsByTagName("name");
var who2 = who[0].textContent.toString();
document.getElementById("who" + i).innerHTML += who2;
var hobby = Customer.getElementsByTagName("hobby");
var hobby2 = hobby[0].textContent.toString();
document.getElementById("hobby" + i).innerHTML += hobby2;
var image = Customer.getElementsByTagName("image");
var image2 = image[0].textContent.toString();
document.getElementById("image" + i).innerHTML += image2;
var something = Customer.getElementsByTagName("something");
var something2 = something[0].textContent.toString();
document.getElementById("something" + i).innerHTML += something2;
}
}

javascript inline code link generating chrome extension

I'm trying to make an extension for chrome that grabs data from a website and I'm having trouble making the links clickable. I CAN NOT use javascript inside the link (ex: href="javascript:myfunction(param);")
I need to create a div for each title, then create a onclick function that handles the div's innerhtml, and I can't get it to work.
here is my code so far:
document.addEventListener('DOMContentLoaded', function () {
$().ready(function () {
var url = 'http://somewebsite';
$.get(url, function (data) {
data = data.split("<tr name=\"hover\">");
var name;
var link;
var count = data.length;
count++;
for(var i = 1; i < data.length; i++){
data[i] = data[i].replace("<br>","<br />");
data[i] = data[i].replace("class=\"thread_link\"", "");
data[i] = data[i].replace("<td class=\"forum_thread_post\" align=\"center\">0</td>","");
data[i] = data[i].replace("<td class=\"forum_thread_post\">","");
data[i] = data[i].replace("</td>","");
data[i] = data[i].replace('<td class="forum_thread_post" align="center">0</td>','');
if(i != data.length-1){
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div><br /><br />");
}else{
data[i] = data[i].split("</table>")[0];
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div>");
}
}
//document.body.innerHTML = '';
//console.log(data);
});
});
});
document.write('</script>');
function getshow(url){
alert(url);
document.body.innerHTML = '';
$.get("http://somewebsite" + url, function (dat) {
document.write(dat);
});
}

WebDB - For each Column, in Each Row

in webDB, EG: HTML5 SQLLite
How can I do the following:
For i = 0 To RS.Fields.Count -1
Response.Write "Field Name: " & RS.Fields(i).Name & "<br>"
Response.Write "Field Value: " & RS(i) & "<br>"
Next
If, at all...
Or, another question would be, how can I iterate the columns themselves and optimally, retrieve the columns name.
I found the answer
function showQueryResults(tx, r) {
// alert("showing [" + r.rows.length.toString() + "] query results");
var rs = null;
var $tr, $td;
var $t = $("<table border='1' cellpadding='2 cellspacing='0' />");
if (r.rows.length > 0) {
rs = r.rows.item(0);
$tr = $("<tr />");
$.each(rs, function (key, val) {
$tr.append($("<th>" + key + "</th>"));
});
$t.append($tr);
for (var i = 0; i < r.rows.length; i++) {
rs = r.rows.item(i);
$tr = $("<tr />");
$.each(rs, function (key, val) {
$tr.append($("<td>" + rs[key] + "</td>"));
});
$t.append($tr);
$tr = null;
};
};
$("#formHolder").children().remove();
$("#formHolder").append($t).show();
$t = null;
};

Categories