-- 作者:hexun831012
-- 发布时间:11/9/2008 12:14:00 PM
-- 发一篇跨浏览器的XMLDOM!
function createDocument() { var oDocument = null; if(window.ActiveXObject) { oDocument = new ActiveXObject("Msxml2.DOMDocument"); } else { oDocument = document.implementation.createDocument("", "", null); } oDocument.async = false; return oDocument; } if(!window.ActiveXObject) { Document.prototype.loadXML = function(sXml) { var oDocument = new DOMParser().parseFromString(sXml, "text/xml"); for(var i = this.childNodes.length; i > 0; i--) { this.removeChild(this.childNodes[i]); } if(oDocument.documentElement.nodeName != "parsererror") { for(var i = 0; i < oDocument.childNodes.length; i++) { this.appendChild(oDocument.childNodes[i]); } } } Node.prototype.createResolver = function(oResolver) { if(oResolver) { return oResolver; } var oNode = this.documentElement ? this.documentElement : this; if(oNode.prefix) { return document.createNSResolver(oNode); } else { return function() { return oNode.namespaceURI; } } } Node.prototype.selectNodes = function(sXpath, oResolver) { var oSnapshots = new XPathEvaluator().evaluate(sXpath, this, this.createResolver(oResolver), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var aNodes = new Array(); for(var i = 0; i < oSnapshots.snapshotLength; i++) { aNodes[i] = oSnapshots.snapshotItem(i); } return aNodes; } Node.prototype.selectSingleNode = function(sXpath, oResolver) { return new XPathEvaluator().evaluate(sXpath, this, this.createResolver(oResolver), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } Node.prototype.transformNode = function(oStylesheet) { var oProcessor = new XSLTProcessor(); oProcessor.importStylesheet(oStylesheet); return oProcessor.transformToFragment(this, this.ownerDocument ? this.ownerDocument : this).xml; } Node.prototype.transformNodeToObject = function(oStylesheet) { var oProcessor = new XSLTProcessor(); oProcessor.importStylesheet(oStylesheet); return oProcessor.transformToDocument(this); } Node.prototype.__defineGetter__("text", function() { return this.textContent; }) Node.prototype.__defineSetter__("text", function(sValue) { this.textContent = sValue; }) Node.prototype.__defineGetter__("xml", function() { return new XMLSerializer().serializeToString(this); }) } 对Moizlla内核的浏览器,可以完全使用IE接口去操作DOM,唯一的区别就是用createDocument()去创建DOM。 该脚本也并不是完美的,第一,目前还不支持异步,但以后会改进的,第二,在XPath方面Mozilla还不支持复杂表达式,所谓复杂表达式就是跨命名空间的XPath,在Mozilla中复杂表达式的命名空间的映射关系完全依赖于手工输入,所以接口方面会有所差别,第三,transformNodeToObject方法是最头疼的,JS不支持引用传递,而IE偏偏是引用传递的,他用COM写的,不管JS死活拉,哇哇哇,老老实实返回出来多好。
|