Home  >  Article  >  Web Front-end  >  JavaScript method to convert xml into html table_javascript skills

JavaScript method to convert xml into html table_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:03:241497browse

The example in this article describes the method of converting xml into html table using JavaScript. Share it with everyone for your reference. The details are as follows:

function ConvertToTable(targetNode)
{
 // if the targetNode is xmlNode this line must be removed
 // i couldnt find a way to parse xml string to xml node
 // so i parse xml string to xml document
 targetNode = targetNode.childNodes[0];
 // first we need to create headers
 var columnCount = targetNode.childNodes[0].childNodes.length;
 var rowCount = targetNode.childNodes.length
 // name for the table
 var myTable = document.createElement("table");
 myTable.border = 1;
 myTable.borderColor ="green";
 var firstRow = myTable.insertRow();
 var firstCell = firstRow.insertCell();
 firstCell.colSpan = columnCount;
 firstCell.innerHTML = targetNode.nodeName;
 // name for the columns
 var secondRow = myTable.insertRow();
 for(var i=0;i<columnCount;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<columnCount;j++)
   {
   var newCell = newRow.insertCell();
   newCell.innerHTML = targetNode.childNodes[i2].childNodes[j].firstChild.nodeValue;
   }
 }
 // i prefer to send it as string instead of a table object
 return myTable.outerHTML;
}

Here is a simple example usage:




 Untitled Page




I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn