Cucurigu Cucurigu - 8 days ago 7
jQuery Question

Create table from XML document with jQuery

I am trying to create a dynamic HTML table from an XML file. There are several major "chapters", under each letter of the alphabet. I want a table to be generated under each letter, with a format similar to this:

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


Here is what the XML file looks like:

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


And here is the jQuery code I'm using to create the table into a div with id="content":

$(document).find("letter").each(function(){
// Define letters variable
$letters = $(this).find('> title').text();

//Find descendants of each letter
$codes = ($(this).find('code').text());
$desc = ($(this)).find('mainTerm title').text();

//Build table
$("#content").append(
'<table border="1"><tr><th>Code</th><th>Description</th></tr><tr><td> '+$codes+' </td><td> '+$desc+' </td></tr></table>'
);
(end brackets for the above)


What I get in the output is a table with just one row for each letter/chapter, with all the codes and all the descriptions lumped together in one cell each.

What I need is a dynamic table where, on each row, I get a single code and its corresponding description. How do I do that?

Answer

        $(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 = $('<tbody></tbody>').append($($.makeArray($xml.find('mainTerm').map(function () {
                return '<tr><td>' + $(this).find('code').text() + '</td><td>' + $(this).find('title').text() + '</td></tr>';
            })).join('')));
            var $table = $('<table><thead><tr><td>Code</td><td>Description</td></tr></thead></table>').append($terms).appendTo($('body'));
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments