views:

4382

answers:

5

I have a variable string that contains well-formed and valid XML. I need to use Javascript to parse this feed.

How can I accomplish this using (browser-compatible) Javascript?

+1  A: 

Please take a look at this. Its a tutorial on XML DOM parsing. The actual DOM parser differs from browser to browser but the DOM API is standardised and remains the same (more or less).


[Update] Alternatively use E4X if you can restrict yourself to Firefox. Its relatively easier to use and its part of Javascript since version 1.6. Here is a small sample usage...

//Using E4X
var xmlDoc=new XML();
xmlDoc.load("note.xml");
document.write(xmlDoc.body);//note 'body' is actually a tag in note.xml 
//but it can be accessed as if it were a regular property of xmlDoc.
SDX2000
+4  A: 

Internet Explorer and for example Mozilla based browsers expose diffirent objects for xml parsing, so it's wise to use a javascript framework like JQuery to handle the cross-browsers differences.

really basic example:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

For more in depth information read this tutorial

Sander Versluys
The code for abstracting out the difference in XML parsing between IE and other browsers is a few trivial lines, so not worth bolting on 50K of jQuery for on its own. Manipulating the resulting XML's DOM is another matter.
Tim Down
+1  A: 

Assuming you want to build a DOM from this XML, sadly you need to use browser-specific interfaces. Here is an attempt at a cross-browser function for doing it, however.

W3Schools also document the individual browser-specific methods.

MattJ
+2  A: 

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}
Cerebrus
-1 for browser sniffing.
Ionuț G. Stan
I am aware of the controversial opinions regarding Browser sniffing and that's the reason I did not include that function here. However, it has not been established that it is WRONG. In any case, this is a *suggestive* example.
Cerebrus
A: 

I've always used the approach below which works in IE and Firefox.

Example XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}
John Topley