0

I'm trying to use some code adapted from using Jquery to get XML and put into html table. It's working almost perfect for what I want apart from the XML file I'm loading includes an attribute ID number for each item, which I can't get to load.

So the XML looks a bit like this..

 <Incidents>
   <Incident id="123">
     <ModTime>2016-01-23T08:00:00Z</ModTime>
     <comments>comments here</severity>
     <currentUpdate>update</currentUpdate>
     <status>Active</status>
   </incident>
 <Incidents>
   <Incident id="456">
     <ModTime>2016-01-23T08:00:00Z</ModTime>
     <comments>comments here</severity>
     <currentUpdate>update</currentUpdate>
     <status>Active</status>
   </incident>

I thought that I could adapt this: How to parse xml attributes with jQuery alone?

<script type='text/javascript'>//<![CDATA[
$.ajax({
type: "GET",
url: "feed.xml",
dataType: "xml",
success: function(xml){
    $('#table').append('<h2>XML</h2>'); 
    $('#table').append('<table id="show_table" border="1" >'); 
    $(xml).find('Incident').each(function(){

        var $feed = $(this);
        var id = $feed.find('Incident').attr('id');
        var mod = $feed.find('ModTime').text();
        var comments = $feed.find('comments').text();
        var update = $feed.find('currentUpdate').text();
        var status = $feed.find('status').text();


        var html = ' <tr><td >' + id + '</td><td >' + mod + '<br>' + comments     + '</td><td>' + update + '</td><td>'  + status +'</td><td > </tr>';
        $('#show_table').append(html);
    });
}
});
</script>

But with that all the ID rows shows is 'undefined' for each incident.

The closest I've managed to get was using...

        var id = $(xml).find("Disruption").attr("id");

but that just shows the same ID number for all rows.

Community
  • 1
  • 1
Rob
  • 35
  • 2

1 Answers1

0
$(xml).find('Incident')

You have got all the Incidents.

var $feed = $(this);

Looping over each Incident, you store the element in $feed

var id = $feed.find('Incident').attr('id');

You then search the descendants of the Incident for further Incidents (and get the id of the first one).

There aren't any Incidents stored inside other Incidents, so you don't find any (and get undefined, which is the id of the 1 of 0 Incident that you checked).

You just want:

var id = $feed.attr("id");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335