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?
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;
};
                        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;      
}
                        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