Alex Borsody
Alex Borsody

Reputation: 2040

parsing xml with javascript WITHOUT AJAX?

I am creating a widget that will be installed across different sites. The widget will parse an XML feed into JPlayer, because the widget will be installed across different sites AJAX is not an option, is there a way to parse XML with javascript without using AJAX. I am trying to stay away from PHP as well.

here is code in Simple XML, but I want to rewrite it in javascript.

$url = 'http://www.startalkradio.net/?page_id=354';
$rss = simplexml_load_file($url);

$items = $rss->channel->item;
<?php


$i = 0;
$data = array();
foreach ($items as $item) {
    $data[] = array(
        'title' => (string) $item->title,
        'mp3'   => (string) $item->enclosure['url'],

    );
    if (++$i == 3) break;
}


$jsdata = json_encode($data);

Upvotes: 0

Views: 1325

Answers (1)

Tim Down
Tim Down

Reputation: 324547

The following will parse and XML string into an XML document in all major browsers, including IE 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Upvotes: 3

Related Questions