简体   繁体   中英

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

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

I'm assuming that you're currently doing an implementation similar to http://www.javascriptkit.com/dhtmltutors/getxml3.shtml

If that's the case, I know it's not pretty but couldn't you simply just wrap it in try/catch? Or, do you need to know if it is XML and specifically not some other type. If that's the case I'm not sure you can without making some other assertions. A try catch will at least allow you to create an XML document from an object without throwing an error to the screen. You could assume then that if it loads into the DOM that it IS valid XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM