简体   繁体   English

使用jQuery进行XML解析并添加到HTML表中

[英]XML parsing using jQuery and append in HTML table

<rows>
<row id='1'>    // parent
<cell>1</cell>
<cell>Task ABC0134</cell>

<row id="2"> // parent
<cell>1</cell>
<cell>Task ABC0134</cell>
</row>

<row id="3"> // parent
<cell>1</cell>
<cell>Task ABC0135</cell>
</row>

<row id="4"> // parent
<cell>1</cell>
<cell>Task ABC0136</cell>
</row>
</row>

I want to parse the above XML file and append that in the HTML table. 我想解析以上XML文件,并将其附加到HTML表中。

I found some code to parse that 我找到了一些代码来解析

$(this).find('cell').each(function(){});

but it gave me the whole cells it contains. 但它给了我其中包含的整个细胞。 I want to take the cells in the first row.but that row is the parent for all the cells. 我想在第一行中获取单元格,但该行是所有单元格的父级。

so how to take that cells separately. 那么如何将这些单元格分开。

Solution & code (Explanation in code comments) 解决方案和代码(代码注释中的说明)

//xml init
var xml = "<rows><row id='1'><cell>1</cell><cell>Task ABC0134</cell><row id='2'><cell>1</cell><cell>Task ABC0134</cell></row><row id='3'> <cell>1</cell><cell>Task ABC0135</cell></row><row id='4'><cell>1</cell><cell>Task ABC0136</cell></row></row>"

//get the first row's id - used for comparison later
var firstRowId = $(xml).find("row:first").attr("id");
//create "tr" string - for appending to table later
var tr = "<tr>";
//iterate over each <cell>
var cells = $(xml).find("cell").each(function (i) {
    //check if current cell's parent (<row>) 's id matches firstRowId
    if ($(this).parent("row").attr("id") === firstRowId) {
        //if yes go in, create <td>
        tr += "<td>" + $(this).text() + "</td>";
    }
});
//finish the string
tr += "</tr>";
//apend to table
$("table").append(tr);

Demo : http://jsfiddle.net/hungerpain/Uf95P/ 演示: http : //jsfiddle.net/hungerpain/Uf95P/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM