Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - How to get xml data

Tags:

jquery

xml

Im a total noob to html, css, javascript, and programming altogether. Please bear with me.

Im trying to populate my table using jquery. The data will be coming from an xml file.

football_player.xml:

<?xml version="1.0" encoding="UTF-8"?>

<football_player>
  <name>Cristiano Ronaldo</name>
  <club>Real Madrid</club>
  <number>7</number>
  <country>Portugal </country>

  <name>Fernando Torres </name>
  <club>Chelsea </club>
  <number>9</number>
  <country>Spain</country>

  <name>Iker Casillas</name>
  <club>Real Madrid </club>
  <number>1</number>
  <country>Spain</country>

  <name>David Beckham</name>
  <club>Los Angeles Galaxy</club>
  <number>23</number>
  <country>England</country>
</football_player>

My html table:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Club</th>
      <th>Number</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
  </tfoot>
  </tfoot>
</table>

My javascript/jquery script:

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "football_player.xml",
    dataType: "xml",
    success: function(xml) {
      $(xml).find("football_player").each(function () {
        $("table tbody").append("<tr>");
        $("table tbody").append("<td>" + $(this).find("name").text() + "</td>");
        $("table tbody").append("<td>" + $(this).find("club").text() + "</td>");
        $("table tbody").append("<td>" + $(this).find("number").text() + "</td>");
        $("table tbody").append("<td>" + $(this).find("country").text() + "</td>");
        $("table tbody").append("</tr>");           
      });
    }
  });
});

I swear Im really a noob. I don't have any idea of what Im doing. Please help. I really want to learn. Thanks in advance.

like image 595
TheOnlyIdiot Avatar asked May 30 '12 07:05

TheOnlyIdiot


People also ask

How to get XML data in jQuery?

$. ajax({ type: "GET", url: "football_player. xml", ->dataType: "text", success: function(xml) { var parser = new DOMParser(); var xmlDoc = parser. parseFromString(xml, "text/xml"); var json = ->getJson(xmlDoc); for(var i =0; i< json[0].

Does jQuery work with XML?

jQuery can be used for XML processing on the Web as well as HTML processing, and in this article I show some examples of this use.

How to load an XML file using jQuery?

Load an XML file using jQuery Load Method. Display it in a HTML table. The HTML table has pagination system. Due to this pagination system the XML data will be shown in page by page manner. This whole thing will be based on AJAX.

How to read XML data from HTML table?

The HTML table has pagination system. Due to this pagination system the XML data will be shown in page by page manner. This whole thing will be based on AJAX. Note: The XML reading method that I will use will support any XML file with any format.

What is an XML file?

XML (Extensible Markup Language), on the other hand, is a language similar to HTML, but with a markedly different function. While the purpose of HTML is to display data, XML just stores data and transports it when necessary. In this tutorial, we’re going to take a look at how you can use JQuery and Ajax code to process and read an XML file.

How to read XML in page by page manner using jQuery?

I loop through all the nodes of the XML file and append them to a table. The appending is done through jQuery Append method. The Paging () function creates the Pagination links using jQuery Pagination, and helps user to read the XML in page by page manner.


2 Answers

The sample XML:

<?xml version="1.0" encoding="utf-8" ?>
  <RecentBooks>
     <Book>
      <Title>My Cool Book Title</Title>
    <Description>The my cool book is possibly the best cool book in that any developer could use to     be a great web designer.</Description>
    <Date>12/1/2010</Date>
    </Book>
    <Book>
     <Title>Another PHP book</Title>
    <Description>Learn everything about PHP with 'Another PHP book,' your ultimate guide to the ins and outs of PHP.</Description>
    <Date>4/1/2010</Date>
    </Book>
    <Book>
    <Title>jQuery Techniques</Title>
    <Description>jQuery techniques runs you through real life examples of jQuery from beginner to expert</Description>
     <Date>6/2/2010</Date>
     </Book>
     <Book>
    <Title>MySQL Database Book</Title>
    <Description>Brush up your knowledge with the best MySQL database book on the market.          </Description>
    <Date>14/2/2010</Date>
    </Book>
  </RecentBooks>

And the HTML & jquery.

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "books.xml",
    dataType: "xml",
    success: xmlParser
  });
});
 
function xmlParser(xml) {
  $('#load').fadeOut();
 
  $(xml).find("Book").each(function () {
    $(".main").append('<div class="book"><div class="title">' + $(this).find("Title").text() + '</div><div class="description">' + $(this).find("Description").text() + '</div><div class="date">Published ' + $(this).find("Date").text() + '</div></div>');
    $(".book").fadeIn(1000);
  });
}

<div class="main">
  <div align="center" class="loader"><img src="loader.gif" id="load" width="16" height="11"   align="absmiddle"/></div>
</div>
 
<div class="clear"></div>

you can go through the example and you will get idea about the same

like image 193
Arnab Shaw Avatar answered Oct 01 '22 14:10

Arnab Shaw


I was in similar problem, where I was fetching XML data using HTTP GET and then parsing. Taking your example:

$.ajax({
    type: "GET",
    url: "football_player.xml",
    ->dataType: "text",
    success: function(xml) {
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(xml, "text/xml");
        var json = ->getJson(xmlDoc);
        for(var i =0; i< json[0].football_player.length;i++) {
            var player = json[0].football_player[i];
            $("table tbody").append("<tr>");
            $("table tbody").append("<td>" + ->player.name + "</td>");
            $("table tbody").append("<td>" + ->player.club + "</td>");
            $("table tbody").append("<td>" + ->player.number + "</td>");
            $("table tbody").append("<td>" + ->player.country + "</td>");
            $("table tbody").append("</tr>");
        }
    }
});

Three things to notice (->):

  1. dataType: "text" I made http request with data type as TEXT rather than XML, so that I get xml data as a string data type.

  2. getJson(xmlDoc) method: I wrote a small function to convert XML to Javascript object (JSON). There are other small utilities available to do the same.

  3. player.name: due to this conversion, you can use XML content as javascript objects and thus easier to parse and read.

I am pasting getJson() function below (its not tested, I made it for a POC, but worked for me):

function getJson(xmlDoc) {
    var result = [];

    for (var i = 0; i < xmlDoc.children.length; i++) {
        var child = xmlDoc.children[i];
        if (result[child.tagName] === undefined) {
            result[child.tagName] = [];
        }

        var nodeJson = getJsonFromNode(xmlDoc.children[i]);
        result[child.tagName].push(nodeJson);
    }

    return result;
}

function getJsonFromNode(node) {
    var nodeJson = {};
    // for attributes
    for (var i = 0; i < node.attributes.length; i++) {
        var att = node.attributes[i];
        nodeJson[att.localName] = att.value;
    }

    // for child nodes
    for (var i = 0; i < node.children.length; i++) {
        var child = node.children[i];
        if (nodeJson[child.tagName] === undefined) {
            nodeJson[child.tagName] = [];
        }
        var result = getJsonFromNode(node.children[i]);
        nodeJson[child.tagName].push(result);
    }

    return nodeJson;
}
like image 29
Savaratkar Avatar answered Oct 02 '22 14:10

Savaratkar