Asked  7 Months ago    Answers:  5   Viewed   47 times

Are there any cross-browser / cross-platform ways to parse XML files in Javascript?

 Answers

24

The following will work in all major browsers, including IE 6:

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);

Live demo:

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");
}

var xml = parseXml("<foo>Stuff</foo>");
document.body.innerHTML = "Root element: " + xml.documentElement.nodeName;
Tuesday, June 1, 2021
 
Vlad
answered 7 Months ago
70

There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers).

Saturday, June 26, 2021
 
tadman
answered 6 Months ago
49

(You cannot have googled a lot.) Once you have worked around the Same Origin Policy, and if the resource is served with an XML MIME type (which it is in this case, text/xml), you can do the following:

var x = new XMLHttpRequest();
x.open("GET", "http://feed.example/", true);
x.onreadystatechange = function () {
  if (x.readyState == 4 && x.status == 200)
  {
    var doc = x.responseXML;
    // …
  }
};
x.send(null);

(See also AJAX, and the XMLHttpRequest Level 2 specification [Working Draft] for other event-handler properties.)

In essence: No parsing necessary. If you then want to access the XML data, use the standard DOM Level 2+ Core or DOM Level 3 XPath methods, e.g.

/* DOM Level 2 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].firstChild.nodeValue;

/* DOM Level 3 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].textContent;

/* DOM Level 3 XPath (not using namespaces) */
var title = doc.evaluate('//channel/title/text()', doc, null, 0, null).iterateNext();

/* DOM Level 3 XPath (using namespaces) */
var namespaceResolver = (function () {
  var prefixMap = {
    media: "http://search.yahoo.com/mrss/",
    ynews: "http://news.yahoo.com/rss/"
  };

  return function (prefix) {
    return prefixMap[prefix] || null;
  };
}());

var url = doc.evaluate('//media:content/@url', doc, namespaceResolver, 0, null).iterateNext();

(See also JSX:xpath.js for a convenient, namespace-aware DOM 3 XPath wrapper that does not use jQuery.)

However, if for some (wrong) reason the MIME type is not an XML MIME type, or if it is not recognized by the DOM implementation as such, you can use one of the parsers built into recent browsers to parse the responseText property value. See pradeek's answer for a solution that works in IE/MSXML. The following should work everywhere else:

var parser = new DOMParser();
var doc = parser.parseFromString(x.responseText, "text/xml");

Proceed as described above.

Use feature tests at runtime to determine the correct code branch for a given implementation. The simplest way is:

if (typeof DOMParser != "undefined")
{
  var parser = new DOMParser();
  // …
}
else if (typeof ActiveXObject != "undefined")
{
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  // …
}

See also DOMParser and HTML5: DOM Parsing and Serialization (Working Draft).

Wednesday, July 28, 2021
 
khaverim
answered 5 Months ago
62

Use this: http://www.w3schools.com/Xml/tryit.asp?filename=tryxml_parsertest2

It parses xml from a string and uses the fast native XML parsing engine from the browser.

Explanation and discussion:

http://www.w3schools.com/Xml/xml_parser.asp

Wednesday, September 1, 2021
 
zerzer
answered 4 Months ago
84

Assuming you are using LESS 1.3.1 or later, then this does what you want (using built in functions):

LESS

//define mixin
.crossbrowser(@color,@alpha){
  @rgba: rgba(red(@color),green(@color),blue(@color),@alpha);
  @argb: argb(@rgba);
  background-color: @color;
  background-color: @rgba;
  filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorstr=@{argb}, endColorstr=@{argb})";
  -ms-filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorstr=@{argb}, endColorstr=@{argb})";
}

//use it
.crossbrowser(red, .2);

CSS Output

background-color: #ff0000;
background-color: rgba(255, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#33ff0000, endColorstr=#33ff0000);
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#33ff0000, endColorstr=#33ff0000);
Sunday, October 10, 2021
 
abrzozowski
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share