admin管理员组文章数量:1316823
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?
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?
-
doc.doctype
is the doctype node. The doctype node should be XHTML rather then html. – Raynos Commented Dec 30, 2011 at 14:39 - My documents aren't XHTML so they have no doctype. But thanks for the tip. – hugomg Commented Dec 30, 2011 at 22:20
3 Answers
Reset to default 3I'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./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.
本文标签: javascriptHow should I test if an object is a XML document (in a cross browser way)Stack Overflow
版权声明:本文标题:javascript - How should I test if an object is a XML document (in a cross browser way) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742000674a2410948.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论