Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning xml string - how to parse xml file using JQuery/Json

Tags:

json

jquery

jsonp

when i do alert it returning string like this:

data    "<?xml version="1.0" encoding="utf-8" ?> 
      <xml xmlns="http://www.opengis.net/kml/2.2">
      <Document>
      <Name>John Smith</Name> 
      <Description>stackoverflow</Description> 
      <Total>50</Total> 
      </Document>
      </xml>"

Update: i tried using this method getJSON and i do get alerts but never execute inside the find('Document').each.....

 $.getJSON(_url, function (data) {

            alert(data);    
            $(data).find('Document').each(function () {
                debugger
                var name = $(this).find('Name');
                var desc = $(this).find('Description').text();
                var total = $(this).find('Total').text()

            });

        });

how to read xml file in jquery, below is what is returning me as a string and i can see that when i do alert(data);

 $.getJSON(url, {},
                function (data) {
                    alert(data);
             }
});


<?xml version="1.0" encoding="utf-8" ?> 
- <xml xmlns="http://www.opengis.net/kml/2.2">
- <Document>
  <Name>John Smith</Name> 
  <Description>stackoverflow</Description> 
  <Total>50</Total> 
  </Document>
  </xml>
like image 818
Nick Kahn Avatar asked Dec 14 '25 22:12

Nick Kahn


1 Answers

If you're still looking for an answer, Google's ajax API has a built in xml->json converter.

You can call it via http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q= with your request url at the end.

If youre trying to use JSONP and get around same origin concerns, it would look something like this:

var googleAPI = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=";

$.getJSON(googleAPI + url + "&callback=?", null, function(data) {

        alert(data);    
        $(data).find('Document').each(function () {
            debugger
            var name = $(this).find('Name');
            var desc = $(this).find('Description').text();
            var total = $(this).find('Total').text()

        });
});

However, this will give you JSON data, so youre going to need to modify your callback to serialize it and access the Name, Description, Total elements as attributes. If you need direction on this, checkout Serializing to JSON in jQuery

like image 186
ginman Avatar answered Dec 16 '25 13:12

ginman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!