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?
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?
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();
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.
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;
}
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);
}
}
}
}
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.
Disclaimer : I've created fast-xml-parser
I have created fast-xml-parser to parse a XML string into JS/JSON object or intermediate traversal object. It is expected to be compatible in all the browsers (however tested on Chrome, Firefox, and IE only).
Usage
var options = { //default
attrPrefix : "@_",
attrNodeName: false,
textNodeName : "#text",
ignoreNonTextNodeAttr : true,
ignoreTextNodeAttr : true,
ignoreNameSpace : true,
ignoreRootElement : false,
textNodeConversion : true,
textAttrConversion : false,
arrayMode : false
};
if(parser.validate(xmlData)){//optional
var jsonObj = parser.parse(xmlData, options);
}
//Intermediate obj
var tObj = parser.getTraversalObj(xmlData,options);
:
var jsonObj = parser.convertToJson(tObj);
Note: It doesn't use DOM parser but parse the string using RE and convert it into JS/JSON object.