Heim  >  Artikel  >  Web-Frontend  >  JavaScript实现将xml转换成html table表格的方法_javascript技巧

JavaScript实现将xml转换成html table表格的方法_javascript技巧

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

本文实例讲述了JavaScript实现将xml转换成html table表格的方法。分享给大家供大家参考。具体如下:

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;
}

下面是一个简单的示例用法:




 Untitled Page




希望本文所述对大家的javascript程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn