Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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

share|improve this question

9 Answers

up vote 52 down vote accepted

Update: For a more correct answer see Tim Down's answer.

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

A really basic example is:

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

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

For more in-depth information, read the tutorial Easy XML Consumption using jQuery.

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

share|improve this answer
3  
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 Sep 24 '09 at 13:29
4  
And something I didn't realise at the time of posting my previous comment is that jQuery doesn't even parse the XML, it simply assigns it as the innerHTML property of an element, which is not at all reliable. – Tim Down Nov 15 '10 at 1:24
9  
This does not parse XML and should not be the accepted answer. – Tim Down Oct 31 '11 at 9:42
4  
This answer is wrong. See stackoverflow.com/questions/2124924/…, stackoverflow.com/questions/2908899/…, @Tim Down's answer and the jQuery documentation itself where it states: "Note that [jQuery()] parses HTML, not XML" – Crescent Fresh Dec 7 '11 at 10:53
1  
@SanderVersluys: since the author is not accepting another answer, I would include a note in your answer linking to @TimDown's correct answer. That way people don't have to read all these comments to figure out the correct answer. – Senseful Jan 24 '12 at 4:44
show 7 more comments

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 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);

If you're using jQuery, from version 1.5 you can use its built-in parseXML() method.

var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
share|improve this answer
Here here. Cripes the question itself is a dupe of so many others, I'll try to track them down. – Crescent Fresh Dec 7 '11 at 10:42
16  
I agree, this should be accepted answer. My answer is so old from the early days, I've always find it curious it still gets upvotes. Anyone in favor of removing my accepted answer? And is the voting system flawed? Upvote this people! – Sander Versluys Dec 8 '11 at 9:41
@SanderVersluys: Are you able to remove your answer? – Witman Mar 2 '12 at 11:57
1  
Had to downvote you for saying that there are 'no other decent answers'. @SanderVersluys answer worked fine in my case. What's not decent about that, I do not know. – Eric Apr 19 '12 at 15:21
1  
@EricTurner: I stand by it and Sander himself has disowned his answer. jQuery docs tell you not to use $() for XML parsing. Read the comments more carefully: it simply does not work in many situations. – Tim Down Apr 19 '12 at 16:07
show 3 more comments

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;
}
share|improve this answer
7  
-1 for browser sniffing. – IonuČ› G. Stan Mar 16 '09 at 9:50
6  
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 Mar 16 '09 at 9:54

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Here's an example of what you can do with Marknote:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}
share|improve this answer

Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5

share|improve this answer

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);
      }
    }
  }
}
share|improve this answer
How would you take a value if you had this situation <fruit>value</fruit> ? – Siblja Sep 14 '11 at 10:40

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.

share|improve this answer

I created a jQuery plugin that parses XML pretty easily. It works in all Yahoo A grade browsers and comes with filtering, limit and callback options.

It might be a solution to consider: http://jparse.kylerush.net/

share|improve this answer

Please take a look at XML DOM Parser (W3Schools). It's 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).

Alternatively use E4X if you can restrict yourself to Firefox. It's relatively easier to use and it's 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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.