Getting Data from XML with jQuery

How do we extract data from XML with jQuery?

 

In this article, we will show you how to extract and use data from XML with JQuery. The subject is very simple and clear. Of course, you first need to have some knowledge of JQuery, AJAX and XML. Therefore, we recommend that you take a look at these topics before starting the article. Moving on to our topic, first we create XML. It's up to you. It can be any XML or it can also be an RSS feed. We created the following XML for testing purposes.

 

<?xml version="1.0" encoding="utf-8" ?>
<Personlist> 
    <Person> 
        <Name>Eleman1</Name> 
        <Position>Birinci</Position>
    </Person> 
    <Person> 
        <Name>Eleman2</Name>
         <Position>İkinci</Position>
    </Person> 
    <Person> 
        <Name>Eleman3</Name> 
        <Position>Üçüncü</Position> 
    </Person> 
</Personlist>

 

 

Then we added the HTML code block and the AJAX control into it as shown below.

 

<!doctype html>
<html>
<head runat="server">
    <title>XML/JSON Deneme</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript"> $(function () {
     $('#getdata').on('click', function () {
         $.ajax({
             url: 'test.xml',
             type: 'GET',
             dataType: 'xml',
             success: function (gelen) {
                 var html = "<table>";
                 $(gelen).find('Person').each(function () {
                     html += "<tr><td><label>Ad:</label>" + $(this).find('Name').text() + "</td><td><label>Pozisyon:</label>" + $(this).find('Position').text() + "</td></tr>";
                 });
                 html += "</table>";
                 $("#showdata").html(html);
             }
         });
     });
 }); </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <a href="#" id="getdata">XML Verilerini Al</a>
            <div id="showdata"></div>
        </div>
    </form>
</body>
</html> 
 

 

As you can see, among the body tags, we first created a link with the "getdata" id and a div with the "showdata" id. Then, $(function(){ //execute when the page is ready. }); which means when the page is ready, is placed between the head tags. In this code block, we prepared the script that fetches the data in XML and writes it into the div with the "showdata" id when the link with the "getdata" id is clicked. The most important point here is to make AJAX's dataType property XML and specify the data source. If the data source is not specified, we will not be able to get results and AJAX will not work correctly.

 

We wish everyone good work.

 

Would you like to have an interview?

We help you with your business's most critical issues and opportunities. How about getting permanent change and results together?