Alfred Francis
Alfred Francis

Reputation: 451

Extracting XML data using javascript

   <!--  http://www.abc.com  -->
    <rss version="2.0">
    <channel>
    <title>SENSEX view</title>
    <link>http://www.abc.com</link>
    <copyright>Copyright 2009, abc</copyright>
    <item>
    <title>
    <![CDATA[ SENSEX : 20263.71 * -382.93 (-1.85 %) ]]>
    </title>
    <link/>
    <pubDate>9/20/2013 4:00:00 PM</pubDate>
    <author>abc</author>
    <guid/>
    </item>
    </channel>
    </rss>

I want to extract "<![CDATA[ SENSEX : 20263.71 * -382.93 (-1.85 %) ]]>" from above XML data in a variable. I am not familiar handling XML using javascript. So i need some help or suggest me some tutorials ??

Here's what i have got :

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "http://rss.xml",
    dataType: "xml",.find("title")
    success: function(xml) {
        $(xml).find("title").each(function(){

            var title = $(this).find('title').text();
            $(this).find('title').each(function()
            {
                alert(title );

            });
        });
    }
});
});
</script>
</head>
<body> 
</body>
</html>

Upvotes: 0

Views: 3744

Answers (1)

Yair Nevet
Yair Nevet

Reputation: 13003

Change your success callback code to:

success: function(xml) {
         $(xml).find('item').each(function(){
                 $(this).find('title').each(function(){
         var title = $(this).text();
         alert(title);
       });
       });
    }

And without jQuery:

xmlDoc=loadXMLDoc("yourFile.xml");
var title = xmlDoc.getElementsByTagName("title")[0];
alert(title);

function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

Upvotes: 1

Related Questions