使用jQuery从XML文档创建表

时间:2016-11-24 01:42:10

标签: jquery xml

我正在尝试从XML文件创建动态HTML表。在字母表的每个字母下面有几个主要的章节"。我希望在每个字母下生成一个表格,其格式类似于:

select project_id,
       case when avg(done_ratio) = 100 then 'done'
            when avg(done_ratio) > 0 then 'working'
            else 'not_start'
       end as status
from your_table
group by project_id

这是XML文件的样子:

SELECT 
CASE WHEN done_ratio == 100 THEN 'done'
     WHEN done_ratio == 0 THEN 'not_start'
     ELSE 'working'
FROM tbl

以下是我用来创建表格的jQuery代码,其中id =" content":

Code       Description
Q87.1      Some description
F44.4      Another description
...

我在输出中得到的是一个表格,每个字母/章节只有一行,所有代码和所有描述都集中在一个单元格中。

我需要的是一个动态表,在每一行中,我得到一个代码及其相应的描述。我怎么做?

1 个答案:

答案 0 :(得分:1)



    var extractTerms = function ($xml, selector) {
        return $.makeArray($xml.find(selector).map(function () {
            var term = {title: $(this).children('title:first').text()};
            var $code = $(this).children('code:first');
            if ($code.length > 0)
            {
                term.code = $code.text();
            }
            else
            {
                term.seeAlso = $(this).children('seeAlso:first').text();
            }
            var terms = extractTerms($(this), 'term');
            if(terms.length > 0)
            {
                term.terms = terms;
            }
            return term;
        }));
    };
    var loadTable = function (terms) {
        var $table = $('<table><thead><tr><td>Code</td><td>Description</td></tr></thead></table>').append($.map(terms, function (e, i) {
            var $row = $('<tr><td>' + (e.code || '') + '</td><td><div>' + e.title + '</div></td></tr>');
            if (e.terms)
            {
                $('<div></div>').append(loadTable(e.terms)).appendTo($row.children('td:nth-child(2)'));
            }
            return $row;
        }));
        return $table;
    };
    $(function () {
        var xml = '<index> <letter> <title>A</title> <mainTerm> <title>Some description</title> <code>Q87.1</code> </mainTerm> <mainTerm> <title>Another description<nemod>(-some) (detail)</nemod></title> <code>F44.4</code> </mainTerm> <mainTerm> <title>A more detailed term</title> <seeAlso>similar terms</seeAlso>   <term level="1"> <title>acute</title> <code>R10.0</code> </term> <term level="1"> <title>angina</title> <code>K55.1</code> </term> </mainTerm> </letter> </index>';
        var $xml = $(xml);
        var terms = extractTerms($xml, 'mainTerm');
        var $table = loadTable(terms);
        $('body').append($table);
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;