test xml

by Jason Rose

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://x2js.googlecode.com/hg/xml2json.js"></script>
<ul id="list"></ul>

JavaScript

$(function() {
  $.ajax({
    url: "https://gist.githubusercontent.com/JimBobUKII/1ecb51bce61b5b03ebad/raw/2f65f896b197b68ece6cbdfa116b8e645f9b732a/data.xml",
    type: "GET",
    dataType: "xml",
  }).done(function(response) {
    var x2js = new X2JS(); // Declare an instance from X2JS().
    var json = {}; // Declare the json object.
    var oSerializer = new XMLSerializer(); // Declare an instance from XMLSerializer().
    // $(response).find("data")[0] contains a document fragment from the response xml.
    var xmlString = oSerializer.serializeToString($(response).find("data")[0]); // Serialize the document fragment into XML string.
    json = x2js.xml_str2json(xmlString); // Convert the XML string to JSON.

    // By using Javascript we can sort array of objects.
    // Sorting the group.
    json.data.food = json.data.food.sort(function(a, b) {
      return a.group.toLowerCase() < b.group.toLowerCase();
    });

    var x = {}; // Declare an object to store the ordered data.
    // json.data.food contains an array of objects.
    for (var i = 0; i < json.data.food.length; ++i) {
      var obj = json.data.food[i];
      if (x[obj.group] === undefined) {
        x[obj.group] = [];
      }
      x[obj.group].push(obj);
    }

    // Sorting the names.
    for (i in x) {
      x[i] = x[i].sort(function(a, b) {
        return b.name.toLowerCase() < a.name.toLowerCase();
      });
    }

    // Printing the list in the page.
    $.each(x, function(a, b) {
      $("#list").append("<li>" + a + "<ul id=\"" + a.replace(" ", "").replace(" ", "") + "\"></ul></li>"); // Print the group values.
      for (var i = 0; i < b.length; i++) {
        $("#list #" + a.replace(" ", "").replace(" ", "")).append("<li><a href=\"#" + b[i].id + "\">" + b[i].name + "</a></li>"); // Print the name of each group.
      }
    });
  });
});