XML parsing in JavaScript is defined as it is one kind of package or library of the software which provides an interface for the client applications to work with an XML document and it is used in JavaScript to transform the XML document into readable form, nowadays in many browsers, the XML parser is already available ...
XML parsing is the process of reading an XML document and providing an interface to the user application for accessing the document. An XML parser is a software apparatus that accomplishes such tasks.
XML parser is a software library or a package that provides interface for client applications to work with XML documents. It checks for proper format of the XML document and may also validate the XML documents. Modern day browsers have built-in XML parsers. The goal of a parser is to transform XML into a readable code.
Updated answer for 2017
The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:
function parseXml(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}
If you need to support IE <= 8, the following will do the job:
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");
}
Once you have a Document
obtained via parseXml
, you can use the usual DOM traversal methods/properties such as childNodes
and getElementsByTagName()
to get the nodes you want.
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, which is functionally identical to the function above.
var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
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;
}
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") + "'"
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With