Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I test if an object is a XML document (in a cross browser way)

Tags:

javascript

xml

For an unit test, I want to be able to check if a certain returned object is a XML document. What is the best way to do so?

I am currently just testing for doc.implementation (the first DOM property that came to mind) but is there a better way? Also, is there a nice way to tell apart XML documents from HTML documents?

like image 998
hugomg Avatar asked Dec 29 '11 19:12

hugomg


2 Answers

I'd have a look at the implementation of jQuery.isXMLDoc for ideas. It turns out that the code itself is in the Sizzle library, here:

Sizzle.isXML = function( elem ) {
    // documentElement is verified for cases where it doesn't yet exist
    // (such as loading iframes in IE - #4833) 
    var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;

    return documentElement ? documentElement.nodeName !== "HTML" : false;
};
like image 77
Douglas Avatar answered Oct 21 '22 06:10

Douglas


function isXML(xmlStr){
  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 {
    return false;
  }

  try {
    parseXml(xmlStr);
  } catch (e) {
    return false;
  }
  return true;      
}
like image 31
Ronnie Royston Avatar answered Oct 21 '22 05:10

Ronnie Royston