📄 sarissa.js
字号:
/***************************************************************************** * * Sarissa XML library version 0.9.3 * Copyright (c) 2003 Manos Batsis, mailto: mbatsis@netsmart.gr * This software is distributed under the Kupu License. See * LICENSE.txt for license text. See the Sarissa homepage at * http://sarissa.sourceforge.net for more information. * *****************************************************************************/// $Id: sarissa.js,v 1.1 2005/03/26 20:31:36 svieujot Exp $/** * <p> * Sarissa is a utility class. Provides factory methods for DOMDocument and XMLHTTP objects between other goodies. * </p> * * @constructor */function Sarissa(){}Sarissa.IS_ENABLED_TRANSFORM_NODE = false;Sarissa.IS_ENABLED_XMLHTTP = false;Sarissa.IS_ENABLED_XSLTPROC = false;Sarissa.IS_ENABLED_SELECT_NODES = false;// some basic browser detection TODO: change thisvar _SARISSA_IS_IE = (navigator.userAgent.toLowerCase().indexOf("msie") > -1)?true:false;var _SARISSA_IS_MOZ = (document.implementation && document.implementation.createDocument)?true:false;var _sarissa_iNsCounter = 0;var _SARISSA_IEPREFIX4XSLPARAM = "";if (_SARISSA_IS_MOZ){ if(XSLTProcessor && XSLTProcessor.prototype){ Sarissa.IS_ENABLED_TRANSFORM_NODE = true; if(XSLTProcessor.prototype.reset){ Sarissa.IS_ENABLED_XSLTPROC = true; }; }; if(XMLHttpRequest && XMLHttpRequest.prototype){ Sarissa.IS_ENABLED_XMLHTTP = true; }; if(document.implementation.hasFeature && document.implementation.hasFeature("XPath", "3.0")){ Sarissa.IS_ENABLED_SELECT_NODES = true; }; /** * <p>Factory method to obtain a new DOM Document object</p> * @argument sUri the namespace of the root node (if any) * @argument sUri the local name of the root node (if any) * @returns a new DOM Document */ Sarissa.getDomDocument = function(sUri, sName){ var oDoc = document.implementation.createDocument(sUri, sName, null); oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false); return oDoc; }; /** * <p>Factory method to obtain a new XMLHTTP Request object</p> * @returns a new XMLHTTP Request object */ Sarissa.getXmlHttpRequest = function() { return new XMLHttpRequest(); }; /** * <p>Attached by an event handler to the load event. Internal use.</p> * @private */ function _sarissa_XMLDocument_onload(){ _sarissa_loadHandler(this); }; /** * <p>Ensures the document was loaded correctly, otherwise sets the * parseError to -1 to indicate something went wrong. Internal use</p> * @private */ function _sarissa_loadHandler(oDoc){ if (!oDoc.documentElement || oDoc.documentElement.tagName == "parsererror") oDoc.parseError = -1; _sarissa_setReadyState(oDoc, 4); }; /** * <p>Sets the readyState property of the given DOM Document object. * Internal use.</p> * @private * @argument oDoc the DOM Document object to fire the * readystatechange event * @argument iReadyState the number to change the readystate property to */ function _sarissa_setReadyState(oDoc, iReadyState){ oDoc.readyState = iReadyState; if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function") oDoc.onreadystatechange(); }; /** * <p>Deletes all child Nodes of the Document. Internal use</p> * @private */ XMLDocument.prototype._sarissa_clearDOM = function(){ while(this.hasChildNodes()) this.removeChild(this.firstChild); }; /** * <p>Replaces the childNodes of the Document object with the childNodes of * the object given as the parameter</p> * @private * @argument oDoc the Document to copy the childNodes from */ XMLDocument.prototype._sarissa_copyDOM = function(oDoc){ this._sarissa_clearDOM(); if(oDoc.nodeType == Node.DOCUMENT_NODE || oDoc.nodeType == Node.DOCUMENT_FRAGMENT_NODE) { var oNodes = oDoc.childNodes; for(var i=0;i<oNodes.length;i++) this.appendChild(this.importNode(oNodes[i], true)); } else if(oDoc.nodeType == Node.ELEMENT_NODE) this.appendChild(this.importNode(oDoc, true)); }; // used to normalise text nodes (for IE's innerText emulation) // i'd appreciate any ideas, regexp is not my strong point var _SARISSA_WSMULT = new RegExp("^\\s*|\\s*$", "g"); var _SARISSA_WSENDS = new RegExp("\\s\\s+", "g"); /** * <p>Used to "normalize" text (trim white space mostly). Internal use</p> * @private */ function _sarissa_normalizeText(sIn){ return sIn.replace(_SARISSA_WSENDS, " ").replace(_SARISSA_WSMULT, " "); }; /** * <p>Parses the String given as parameter to build the document content * for the object, exactly like IE's loadXML()</p> * @argument strXML The XML String to load as the Document's childNodes * @returns the old Document structure serialized as an XML String */ XMLDocument.prototype.loadXML = function(strXML){ _sarissa_setReadyState(this, 1); var sOldXML = this.xml; var oDoc = (new DOMParser()).parseFromString(strXML, "text/xml"); _sarissa_setReadyState(this, 2); this._sarissa_copyDOM(oDoc); _sarissa_setReadyState(this, 3); _sarissa_loadHandler(this); return sOldXML; }; /** * <p>Emulates IE's xml property, giving read-only access to the XML tree * in it's serialized form (in other words, an XML string)</p> * @uses Mozilla's XMLSerializer class. */ XMLDocument.prototype.__defineGetter__("xml", function (){ return (new XMLSerializer()).serializeToString(this); }); /** * <p>Emulates IE's xml property, giving read-only access to the XML tree * in it's serialized form (in other words, an XML string)</p> * @uses Mozilla's XMLSerializer class. */ Node.prototype.__defineGetter__("xml", function (){ return (new XMLSerializer()).serializeToString(this); }); /** * <p>Ensures and informs the xml property is read only</p> * @throws an "Invalid assignment on read-only property" error. */ XMLDocument.prototype.__defineSetter__("xml", function (){ throw "Invalid assignment on read-only property 'xml'. Hint: Use the 'loadXML(String xml)' method instead. (original exception: "+e+")"; }); /** * <p>Emulates IE's innerText (read/write). Note that this removes all * childNodes of an HTML Element and just replaces it with a textNode</p> */ HTMLElement.prototype.innerText; HTMLElement.prototype.__defineSetter__("innerText", function (sText){ var s = "" + sText; this.innerHTML = s.replace(/\&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }); HTMLElement.prototype.__defineGetter__("innerText", function (){ var s = this.innerHTML; return s ? _sarissa_normalizeText( s.replace(/<[^>]+>/g, "")) : ""; }); /** * <p>Emulate IE's onreadystatechange attribute</p> */ Document.prototype.onreadystatechange = null; /** * <p>Emulate IE's parseError attribute</p> */ Document.prototype.parseError = 0; /** * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p> * <ul><li>1 == LOADING,</li> * <li>2 == LOADED,</li> * <li>3 == INTERACTIVE,</li> * <li>4 == COMPLETED</li></ul> */ XMLDocument.prototype.readyState = 0; // NOTE: setting async to false will only work with documents // called over HTTP (meaning a server), not the local file system, // unless you are using Moz 1.4+. // BTW the try>catch block is for 1.4; I haven't found a way to check if // the property is implemented without // causing an error and I dont want to use user agent stuff for that... var _SARISSA_SYNC_NON_IMPLEMENTED = false; try{ /** * <p>Emulates IE's async property for Moz versions prior to 1.4. * It controls whether loading of remote XML files works * synchronously or asynchronously.</p> */ XMLDocument.prototype.async = true; _SARISSA_SYNC_NON_IMPLEMENTED = true; }catch(e){/* trap */} /** * <p>Keeps a handle to the original load() method. Internal use and only * if Mozilla version is lower than 1.4</p> * @private */ XMLDocument.prototype._sarissa_load = XMLDocument.prototype.load; /** * <p>Overrides the original load method to provide synchronous loading for * Mozilla versions prior to 1.4, using an XMLHttpRequest object (if * async is set to false)</p> * @returns the DOM Object as it was before the load() call (may be empty) */ XMLDocument.prototype.load = function(sURI){ var oDoc = document.implementation.createDocument("", "", null); oDoc._sarissa_copyDOM(this); this.parseError = 0; _sarissa_setReadyState(this, 1); try{ if(this.async == false && _SARISSA_SYNC_NON_IMPLEMENTED){ var tmp = new XMLHttpRequest(); tmp.open("GET", sURI, false); tmp.send(null); _sarissa_setReadyState(this, 2); this._sarissa_copyDOM(tmp.responseXML); _sarissa_setReadyState(this, 3); } else this._sarissa_load(sURI); }catch (objException) { this.parseError = -1; }finally{ if(this.async == false) _sarissa_loadHandler(this); }; return oDoc; }; /** * <p>Extends the Element class to emulate IE's transformNodeToObject. * <b>Note </b>: The transformation result <i>must </i> be well formed, * otherwise an error will be thrown</p> * @uses Mozilla's XSLTProcessor * @deprecated * @argument xslDoc The stylesheet to use (a DOM Document instance) * @argument oResult The Document to store the transformation result */ Element.prototype.transformNodeToObject = function(xslDoc, oResult){ var oDoc = document.implementation.createDocument("", "", null); oDoc._sarissa_copyDOM(this); oDoc.transformNodeToObject(xslDoc, oResult); }; /** * <p>Extends the Document class to emulate IE's transformNodeToObject</p> * @uses Mozilla's XSLTProcessor * @deprecated * @argument xslDoc The stylesheet to use (a DOM Document instance) * @argument oResult The Document to store the transformation result * @throws Errors that try to be informative */ Document.prototype.transformNodeToObject = function(xslDoc, oResult){ var xsltProcessor = null; try{ xsltProcessor = new XSLTProcessor(); if(xsltProcessor.reset){ /* new nsIXSLTProcessor is available */ xsltProcessor.importStylesheet(xslDoc); var newFragment = xsltProcessor.transformToFragment(this, oResult); oResult._sarissa_copyDOM(newFragment); }else{ /* only nsIXSLTProcessorObsolete is available */ xsltProcessor.transformDocument(this, xslDoc, oResult, null); }; }catch(e){ if(xslDoc && oResult) throw "Failed to transform document. (original exception: "+e+")"; else if(!xslDoc) throw "No Stylesheet Document was provided. (original exception: "+e+")"; else if(!oResult) throw "No Result Document was provided. (original exception: "+e+")"; else if(xsltProcessor == null) throw "Could not instantiate an XSLTProcessor object. (original exception: "+e+")"; else throw e; }; }; /** * <p>Extends the Element class to emulate IE's transformNode. </p> * <p><b>Note </b>: The result of your transformation must be well formed, * otherwise you will get an error</p> * @uses Mozilla's XSLTProcessor * @deprecated * @argument xslDoc The stylesheet to use (a DOM Document instance) * @returns the result of the transformation serialized to an XML String */ Element.prototype.transformNode = function(xslDoc){ var oDoc = document.implementation.createDocument("", "", null); oDoc._sarissa_copyDOM(this); return oDoc.transformNode(xslDoc); }; /** * <p>Extends the Document class to emulate IE's transformNode.</p> * <p><b>Note </b>: The result of your transformation must be well formed, * otherwise you will get an error</p> * @uses Mozilla's XSLTProcessor * @deprecated * @argument xslDoc The stylesheet to use (a DOM Document instance) * @returns the result of the transformation serialized to an XML String */ Document.prototype.transformNode = function(xslDoc){ var out = document.implementation.createDocument("", "", null); this.transformNodeToObject(xslDoc, out); var str = null; try{ var serializer = new XMLSerializer(); str = serializer.serializeToString(out); }catch(e){ throw "Failed to serialize result document. (original exception: "+e+")"; }; return str; }; /** * <p>SarissaNodeList behaves as a NodeList but is only used as a result to <code>selectNodes</code>, * so it also has some properties IEs proprietery object features.</p> * @private * @constructor * @argument i the (initial) list size */ function SarissaNodeList(i){ this.length = i; }; /** <p>Set an Array as the prototype object</p> */ SarissaNodeList.prototype = new Array(0); /** <p>Inherit the Array constructor </p> */ SarissaNodeList.prototype.constructor = Array; /** * <p>Returns the node at the specified index or null if the given index * is greater than the list size or less than zero </p> * <p><b>Note</b> that in ECMAScript you can also use the square-bracket * array notation instead of calling <code>item</code> * @argument i the index of the member to return * @returns the member corresponding to the given index */ SarissaNodeList.prototype.item = function(i) { return (i < 0 || i >= this.length)?null:this[i]; }; /** * <p>Emulate IE's expr property * (Here the SarissaNodeList object is given as the result of selectNodes).</p> * @returns the XPath expression passed to selectNodes that resulted in * this SarissaNodeList */ SarissaNodeList.prototype.expr = ""; /** dummy, used to accept IE's stuff without throwing errors */ XMLDocument.prototype.setProperty = function(x,y){}; /** * <p>Programmatically control namespace URI/prefix mappings for XPath * queries.</p> * <p>This method comes especially handy when used to apply XPath queries
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -