2 * ====================================================================
3 * About Sarissa: http://dev.abiss.gr/sarissa
4 * ====================================================================
5 * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
6 * The library supports Gecko based browsers like Mozilla and Firefox,
7 * Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and Opera
8 * @author: Copyright 2004-2007 Emmanouil Batsis, mailto: mbatsis at users full stop sourceforge full stop net
9 * ====================================================================
11 * ====================================================================
12 * Sarissa is free software distributed under the GNU GPL version 2 (see <a href="gpl.txt">gpl.txt</a>) or higher,
13 * GNU LGPL version 2.1 (see <a href="lgpl.txt">lgpl.txt</a>) or higher and Apache Software License 2.0 or higher
14 * (see <a href="asl.txt">asl.txt</a>). This means you can choose one of the three and use that if you like. If
15 * you make modifications under the ASL, i would appreciate it if you submitted those.
16 * In case your copy of Sarissa does not include the license texts, you may find
17 * them online in various formats at <a href="http://www.gnu.org">http://www.gnu.org</a> and
18 * <a href="http://www.apache.org">http://www.apache.org</a>.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
21 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
22 * WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE
23 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
24 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 * <p>Sarissa is a utility class. Provides "static" methods for DOMDocument,
31 * DOM Node serialization to XML strings and other utility goodies.</p>
36 Sarissa
.VERSION
= "0.9.9.3";
37 Sarissa
.PARSED_OK
= "Document contains no parsing errors";
38 Sarissa
.PARSED_EMPTY
= "Document is empty";
39 Sarissa
.PARSED_UNKNOWN_ERROR
= "Not well-formed or other error";
40 Sarissa
.IS_ENABLED_TRANSFORM_NODE
= false;
41 Sarissa
.REMOTE_CALL_FLAG
= "gr.abiss.sarissa.REMOTE_CALL_FLAG";
43 Sarissa
._sarissa_iNsCounter
= 0;
45 Sarissa
._SARISSA_IEPREFIX4XSLPARAM
= "";
47 Sarissa
._SARISSA_HAS_DOM_IMPLEMENTATION
= document
.implementation
&& true;
49 Sarissa
._SARISSA_HAS_DOM_CREATE_DOCUMENT
= Sarissa
._SARISSA_HAS_DOM_IMPLEMENTATION
&& document
.implementation
.createDocument
;
51 Sarissa
._SARISSA_HAS_DOM_FEATURE
= Sarissa
._SARISSA_HAS_DOM_IMPLEMENTATION
&& document
.implementation
.hasFeature
;
53 Sarissa
._SARISSA_IS_MOZ
= Sarissa
._SARISSA_HAS_DOM_CREATE_DOCUMENT
&& Sarissa
._SARISSA_HAS_DOM_FEATURE
;
55 Sarissa
._SARISSA_IS_SAFARI
= navigator
.userAgent
.toLowerCase().indexOf("safari") != -1 || navigator
.userAgent
.toLowerCase().indexOf("konqueror") != -1;
57 Sarissa
._SARISSA_IS_SAFARI_OLD
= Sarissa
._SARISSA_IS_SAFARI
&& (parseInt((navigator
.userAgent
.match(/AppleWebKit\/(\d+)/)||{})[1], 10) < 420);
59 Sarissa
._SARISSA_IS_IE
= document
.all
&& window
.ActiveXObject
&& navigator
.userAgent
.toLowerCase().indexOf("msie") > -1 && navigator
.userAgent
.toLowerCase().indexOf("opera") == -1;
61 Sarissa
._SARISSA_IS_OPERA
= navigator
.userAgent
.toLowerCase().indexOf("opera") != -1;
62 if(!window
.Node
|| !Node
.ELEMENT_NODE
){
63 Node
= {ELEMENT_NODE
: 1, ATTRIBUTE_NODE
: 2, TEXT_NODE
: 3, CDATA_SECTION_NODE
: 4, ENTITY_REFERENCE_NODE
: 5, ENTITY_NODE
: 6, PROCESSING_INSTRUCTION_NODE
: 7, COMMENT_NODE
: 8, DOCUMENT_NODE
: 9, DOCUMENT_TYPE_NODE
: 10, DOCUMENT_FRAGMENT_NODE
: 11, NOTATION_NODE
: 12};
66 //This breaks for(x in o) loops in the old Safari
67 if(Sarissa
._SARISSA_IS_SAFARI_OLD
){
68 HTMLHtmlElement
= document
.createElement("html").constructor;
69 Node
= HTMLElement
= {};
70 HTMLElement
.prototype = HTMLHtmlElement
.__proto__
.__proto__
;
71 HTMLDocument
= Document
= document
.constructor;
72 var x
= new DOMParser();
73 XMLDocument
= x
.constructor;
74 Element
= x
.parseFromString("<Single />", "text/xml").documentElement
.constructor;
77 if(typeof XMLDocument
== "undefined" && typeof Document
!="undefined"){ XMLDocument
= Document
; }
80 if(Sarissa
._SARISSA_IS_IE
){
81 // for XSLT parameter names, prefix needed by IE
82 Sarissa
._SARISSA_IEPREFIX4XSLPARAM
= "xsl:";
83 // used to store the most recent ProgID available out of the above
84 var _SARISSA_DOM_PROGID
= "";
85 var _SARISSA_XMLHTTP_PROGID
= "";
86 var _SARISSA_DOM_XMLWRITER
= "";
88 * Called when the sarissa.js file is parsed, to pick most recent
89 * ProgIDs for IE, then gets destroyed.
92 * @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object
93 * @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled
95 Sarissa
.pickRecentProgID = function (idList
){
97 var bFound
= false, e
;
99 for(var i
=0; i
< idList
.length
&& !bFound
; i
++){
101 var oDoc
= new ActiveXObject(idList
[i
]);
104 }catch (objException
){
105 // trap; try next progID
110 throw "Could not retrieve a valid progID of Class: " + idList
[idList
.length
-1]+". (original exception: "+e
+")";
115 // pick best available MSXML progIDs
116 _SARISSA_DOM_PROGID
= null;
117 _SARISSA_THREADEDDOM_PROGID
= null;
118 _SARISSA_XSLTEMPLATE_PROGID
= null;
119 _SARISSA_XMLHTTP_PROGID
= null;
120 // commenting the condition out; we need to redefine XMLHttpRequest
121 // anyway as IE7 hardcodes it to MSXML3.0 causing version problems
122 // between different activex controls
123 //if(!window.XMLHttpRequest){
125 * Emulate XMLHttpRequest
128 XMLHttpRequest = function() {
129 if(!_SARISSA_XMLHTTP_PROGID
){
130 _SARISSA_XMLHTTP_PROGID
= Sarissa
.pickRecentProgID(["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]);
132 return new ActiveXObject(_SARISSA_XMLHTTP_PROGID
);
135 // we dont need this anymore
136 //============================================
137 // Factory methods (IE)
138 //============================================
139 // see non-IE version
140 Sarissa
.getDomDocument = function(sUri
, sName
){
141 if(!_SARISSA_DOM_PROGID
){
142 _SARISSA_DOM_PROGID
= Sarissa
.pickRecentProgID(["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]);
144 var oDoc
= new ActiveXObject(_SARISSA_DOM_PROGID
);
145 // if a root tag name was provided, we need to load it in the DOM object
147 // create an artifical namespace prefix
148 // or reuse existing prefix if applicable
151 if(sName
.indexOf(":") > 1){
152 prefix
= sName
.substring(0, sName
.indexOf(":"));
153 sName
= sName
.substring(sName
.indexOf(":")+1);
155 prefix
= "a" + (Sarissa
._sarissa_iNsCounter
++);
158 // use namespaces if a namespace URI exists
160 oDoc
.loadXML('<' + prefix
+':'+sName
+ " xmlns:" + prefix
+ "=\"" + sUri
+ "\"" + " />");
162 oDoc
.loadXML('<' + sName
+ " />");
167 // see non-IE version
168 Sarissa
.getParseErrorText = function (oDoc
) {
169 var parseErrorText
= Sarissa
.PARSED_OK
;
170 if(oDoc
&& oDoc
.parseError
&& oDoc
.parseError
.errorCode
&& oDoc
.parseError
.errorCode
!= 0){
171 parseErrorText
= "XML Parsing Error: " + oDoc
.parseError
.reason
+
172 "\nLocation: " + oDoc
.parseError
.url
+
173 "\nLine Number " + oDoc
.parseError
.line
+ ", Column " +
174 oDoc
.parseError
.linepos
+
175 ":\n" + oDoc
.parseError
.srcText
+
177 for(var i
= 0; i
< oDoc
.parseError
.linepos
;i
++){
178 parseErrorText
+= "-";
180 parseErrorText
+= "^\n";
182 else if(oDoc
.documentElement
=== null){
183 parseErrorText
= Sarissa
.PARSED_EMPTY
;
185 return parseErrorText
;
187 // see non-IE version
188 Sarissa
.setXpathNamespaces = function(oDoc
, sNsSet
) {
189 oDoc
.setProperty("SelectionLanguage", "XPath");
190 oDoc
.setProperty("SelectionNamespaces", sNsSet
);
193 * A class that reuses the same XSLT stylesheet for multiple transforms.
196 XSLTProcessor = function(){
197 if(!_SARISSA_XSLTEMPLATE_PROGID
){
198 _SARISSA_XSLTEMPLATE_PROGID
= Sarissa
.pickRecentProgID(["Msxml2.XSLTemplate.6.0", "MSXML2.XSLTemplate.3.0"]);
200 this.template
= new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID
);
201 this.processor
= null;
204 * Imports the given XSLT DOM and compiles it to a reusable transform
205 * <b>Note:</b> If the stylesheet was loaded from a URL and contains xsl:import or xsl:include elements,it will be reloaded to resolve those
206 * @argument xslDoc The XSLT DOMDocument to import
208 XSLTProcessor
.prototype.importStylesheet = function(xslDoc
){
209 if(!_SARISSA_THREADEDDOM_PROGID
){
210 _SARISSA_THREADEDDOM_PROGID
= Sarissa
.pickRecentProgID(["MSXML2.FreeThreadedDOMDocument.6.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
212 xslDoc
.setProperty("SelectionLanguage", "XPath");
213 xslDoc
.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
214 // convert stylesheet to free threaded
215 var converted
= new ActiveXObject(_SARISSA_THREADEDDOM_PROGID
);
216 // make included/imported stylesheets work if exist and xsl was originally loaded from url
218 converted
.resolveExternals
= true;
219 converted
.setProperty("AllowDocumentFunction", true);
222 // Ignore. "AllowDocumentFunction" is only supported in MSXML 3.0 SP4 and later.
224 if(xslDoc
.url
&& xslDoc
.selectSingleNode("//xsl:*[local-name() = 'import' or local-name() = 'include']") != null){
225 converted
.async
= false;
226 converted
.load(xslDoc
.url
);
229 converted
.loadXML(xslDoc
.xml
);
231 converted
.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
232 var output
= converted
.selectSingleNode("//xsl:output");
233 //this.outputMethod = output ? output.getAttribute("method") : "html";
235 this.outputMethod
= output
.getAttribute("method");
238 delete this.outputMethod
;
240 this.template
.stylesheet
= converted
;
241 this.processor
= this.template
.createProcessor();
242 // for getParameter and clearParameters
247 * Transform the given XML DOM and return the transformation result as a new DOM document
248 * @argument sourceDoc The XML DOMDocument to transform
249 * @return The transformation result as a DOM Document
251 XSLTProcessor
.prototype.transformToDocument = function(sourceDoc
){
252 // fix for bug 1549749
254 if(_SARISSA_THREADEDDOM_PROGID
){
255 this.processor
.input
=sourceDoc
;
256 outDoc
=new ActiveXObject(_SARISSA_DOM_PROGID
);
257 this.processor
.output
=outDoc
;
258 this.processor
.transform();
262 if(!_SARISSA_DOM_XMLWRITER
){
263 _SARISSA_DOM_XMLWRITER
= Sarissa
.pickRecentProgID(["Msxml2.MXXMLWriter.6.0", "Msxml2.MXXMLWriter.3.0", "MSXML2.MXXMLWriter", "MSXML.MXXMLWriter", "Microsoft.XMLDOM"]);
265 this.processor
.input
= sourceDoc
;
266 outDoc
= new ActiveXObject(_SARISSA_DOM_XMLWRITER
);
267 this.processor
.output
= outDoc
;
268 this.processor
.transform();
269 var oDoc
= new ActiveXObject(_SARISSA_DOM_PROGID
);
270 oDoc
.loadXML(outDoc
.output
+"");
276 * Transform the given XML DOM and return the transformation result as a new DOM fragment.
277 * <b>Note</b>: The xsl:output method must match the nature of the owner document (XML/HTML).
278 * @argument sourceDoc The XML DOMDocument to transform
279 * @argument ownerDoc The owner of the result fragment
280 * @return The transformation result as a DOM Document
282 XSLTProcessor
.prototype.transformToFragment = function (sourceDoc
, ownerDoc
) {
283 this.processor
.input
= sourceDoc
;
284 this.processor
.transform();
285 var s
= this.processor
.output
;
286 var f
= ownerDoc
.createDocumentFragment();
288 if (this.outputMethod
== 'text') {
289 f
.appendChild(ownerDoc
.createTextNode(s
));
290 } else if (ownerDoc
.body
&& ownerDoc
.body
.innerHTML
) {
291 container
= ownerDoc
.createElement('div');
292 container
.innerHTML
= s
;
293 while (container
.hasChildNodes()) {
294 f
.appendChild(container
.firstChild
);
298 var oDoc
= new ActiveXObject(_SARISSA_DOM_PROGID
);
299 if (s
.substring(0, 5) == '<?xml') {
300 s
= s
.substring(s
.indexOf('?>') + 2);
302 var xml
= ''.concat('<my>', s
, '</my>');
304 container
= oDoc
.documentElement
;
305 while (container
.hasChildNodes()) {
306 f
.appendChild(container
.firstChild
);
313 * Set global XSLT parameter of the imported stylesheet
314 * @argument nsURI The parameter namespace URI
315 * @argument name The parameter base name
316 * @argument value The new parameter value
318 XSLTProcessor
.prototype.setParameter = function(nsURI
, name
, value
){
319 // make value a zero length string if null to allow clearing
320 value
= value
? value
: "";
321 // nsURI is optional but cannot be null
323 this.processor
.addParameter(name
, value
, nsURI
);
325 this.processor
.addParameter(name
, value
);
327 // update updated params for getParameter
328 nsURI
= "" + (nsURI
|| "");
329 if(!this.paramsSet
[nsURI
]){
330 this.paramsSet
[nsURI
] = [];
332 this.paramsSet
[nsURI
][name
] = value
;
335 * Gets a parameter if previously set by setParameter. Returns null
337 * @argument name The parameter base name
338 * @argument value The new parameter value
339 * @return The parameter value if reviously set by setParameter, null otherwise
341 XSLTProcessor
.prototype.getParameter = function(nsURI
, name
){
342 nsURI
= "" + (nsURI
|| "");
343 if(this.paramsSet
[nsURI
] && this.paramsSet
[nsURI
][name
]){
344 return this.paramsSet
[nsURI
][name
];
351 * Clear parameters (set them to default values as defined in the stylesheet itself)
353 XSLTProcessor
.prototype.clearParameters = function(){
354 for(var nsURI
in this.paramsSet
){
355 for(var name
in this.paramsSet
[nsURI
]){
357 this.processor
.addParameter(name
, "", nsURI
);
359 this.processor
.addParameter(name
, "");
365 }else{ /* end IE initialization, try to deal with real browsers now ;-) */
366 if(Sarissa
._SARISSA_HAS_DOM_CREATE_DOCUMENT
){
368 * <p>Ensures the document was loaded correctly, otherwise sets the
369 * parseError to -1 to indicate something went wrong. Internal use</p>
372 Sarissa
.__handleLoad__ = function(oDoc
){
373 Sarissa
.__setReadyState__(oDoc
, 4);
376 * <p>Attached by an event handler to the load event. Internal use.</p>
379 _sarissa_XMLDocument_onload = function(){
380 Sarissa
.__handleLoad__(this);
383 * <p>Sets the readyState property of the given DOM Document object.
387 * @argument oDoc the DOM Document object to fire the
388 * readystatechange event
389 * @argument iReadyState the number to change the readystate property to
391 Sarissa
.__setReadyState__ = function(oDoc
, iReadyState
){
392 oDoc
.readyState
= iReadyState
;
393 oDoc
.readystate
= iReadyState
;
394 if (oDoc
.onreadystatechange
!= null && typeof oDoc
.onreadystatechange
== "function") {
395 oDoc
.onreadystatechange();
399 Sarissa
.getDomDocument = function(sUri
, sName
){
400 var oDoc
= document
.implementation
.createDocument(sUri
?sUri
:null, sName
?sName
:null, null);
401 if(!oDoc
.onreadystatechange
){
404 * <p>Emulate IE's onreadystatechange attribute</p>
406 oDoc
.onreadystatechange
= null;
408 if(!oDoc
.readyState
){
410 * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p>
411 * <ul><li>1 == LOADING,</li>
412 * <li>2 == LOADED,</li>
413 * <li>3 == INTERACTIVE,</li>
414 * <li>4 == COMPLETED</li></ul>
418 oDoc
.addEventListener("load", _sarissa_XMLDocument_onload
, false);
421 if(window
.XMLDocument
){
423 }// TODO: check if the new document has content before trying to copynodes, check for error handling in DOM 3 LS
424 else if(Sarissa
._SARISSA_HAS_DOM_FEATURE
&& window
.Document
&& !Document
.prototype.load
&& document
.implementation
.hasFeature('LS', '3.0')){
425 //Opera 9 may get the XPath branch which gives creates XMLDocument, therefore it doesn't reach here which is good
427 * <p>Factory method to obtain a new DOM Document object</p>
429 * @argument sUri the namespace of the root node (if any)
430 * @argument sUri the local name of the root node (if any)
431 * @returns a new DOM Document
433 Sarissa
.getDomDocument = function(sUri
, sName
){
434 var oDoc
= document
.implementation
.createDocument(sUri
?sUri
:null, sName
?sName
:null, null);
439 Sarissa
.getDomDocument = function(sUri
, sName
){
440 var oDoc
= document
.implementation
.createDocument(sUri
?sUri
:null, sName
?sName
:null, null);
441 // looks like safari does not create the root element for some unknown reason
442 if(oDoc
&& (sUri
|| sName
) && !oDoc
.documentElement
){
443 oDoc
.appendChild(oDoc
.createElementNS(sUri
, sName
));
448 }//if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT)
450 //==========================================
452 //==========================================
453 if(!window
.DOMParser
){
454 if(Sarissa
._SARISSA_IS_SAFARI
){
456 * DOMParser is a utility class, used to construct DOMDocuments from XML strings
459 DOMParser = function() { };
461 * Construct a new DOM Document from the given XMLstring
462 * @param sXml the given XML string
463 * @param contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml).
464 * @return a new DOM Document from the given XML string
466 DOMParser
.prototype.parseFromString = function(sXml
, contentType
){
467 var xmlhttp
= new XMLHttpRequest();
468 xmlhttp
.open("GET", "data:text/xml;charset=utf-8," + encodeURIComponent(sXml
), false);
470 return xmlhttp
.responseXML
;
472 }else if(Sarissa
.getDomDocument
&& Sarissa
.getDomDocument() && Sarissa
.getDomDocument(null, "bar").xml
){
473 DOMParser = function() { };
474 DOMParser
.prototype.parseFromString = function(sXml
, contentType
){
475 var doc
= Sarissa
.getDomDocument();
482 if((typeof(document
.importNode
) == "undefined") && Sarissa
._SARISSA_IS_IE
){
485 * Implementation of importNode for the context window document in IE.
486 * If <code>oNode</code> is a TextNode, <code>bChildren</code> is ignored.
487 * @param oNode the Node to import
488 * @param bChildren whether to include the children of oNode
489 * @returns the imported node for further use
491 document
.importNode = function(oNode
, bChildren
){
493 if (oNode
.nodeName
=='#text') {
494 return document
.createTextNode(oNode
.data
);
497 if(oNode
.nodeName
== "tbody" || oNode
.nodeName
== "tr"){
498 tmp
= document
.createElement("table");
500 else if(oNode
.nodeName
== "td"){
501 tmp
= document
.createElement("tr");
503 else if(oNode
.nodeName
== "option"){
504 tmp
= document
.createElement("select");
507 tmp
= document
.createElement("div");
510 tmp
.innerHTML
= oNode
.xml
? oNode
.xml
: oNode
.outerHTML
;
512 tmp
.innerHTML
= oNode
.xml
? oNode
.cloneNode(false).xml
: oNode
.cloneNode(false).outerHTML
;
514 return tmp
.getElementsByTagName("*")[0];
519 if(!Sarissa
.getParseErrorText
){
521 * <p>Returns a human readable description of the parsing error. Usefull
522 * for debugging. Tip: append the returned error string in a <pre>
523 * element if you want to render it.</p>
524 * <p>Many thanks to Christian Stocker for the initial patch.</p>
526 * @argument oDoc The target DOM document
527 * @returns The parsing error description of the target Document in
528 * human readable form (preformated text)
530 Sarissa
.getParseErrorText = function (oDoc
){
531 var parseErrorText
= Sarissa
.PARSED_OK
;
532 if(!oDoc
.documentElement
){
533 parseErrorText
= Sarissa
.PARSED_EMPTY
;
534 } else if(oDoc
.documentElement
.tagName
== "parsererror"){
535 parseErrorText
= oDoc
.documentElement
.firstChild
.data
;
536 parseErrorText
+= "\n" + oDoc
.documentElement
.firstChild
.nextSibling
.firstChild
.data
;
537 } else if(oDoc
.getElementsByTagName("parsererror").length
> 0){
538 var parsererror
= oDoc
.getElementsByTagName("parsererror")[0];
539 parseErrorText
= Sarissa
.getText(parsererror
, true)+"\n";
540 } else if(oDoc
.parseError
&& oDoc
.parseError
.errorCode
!= 0){
541 parseErrorText
= Sarissa
.PARSED_UNKNOWN_ERROR
;
543 return parseErrorText
;
547 * Get a string with the concatenated values of all string nodes under the given node
549 * @argument oNode the given DOM node
550 * @argument deep whether to recursively scan the children nodes of the given node for text as well. Default is <code>false</code>
552 Sarissa
.getText = function(oNode
, deep
){
554 var nodes
= oNode
.childNodes
;
555 for(var i
=0; i
< nodes
.length
; i
++){
557 var nodeType
= node
.nodeType
;
558 if(nodeType
== Node
.TEXT_NODE
|| nodeType
== Node
.CDATA_SECTION_NODE
){
560 } else if(deep
=== true && (nodeType
== Node
.ELEMENT_NODE
|| nodeType
== Node
.DOCUMENT_NODE
|| nodeType
== Node
.DOCUMENT_FRAGMENT_NODE
)){
561 s
+= Sarissa
.getText(node
, true);
566 if(!window
.XMLSerializer
&& Sarissa
.getDomDocument
&& Sarissa
.getDomDocument("","foo", null).xml
){
568 * Utility class to serialize DOM Node objects to XML strings
571 XMLSerializer = function(){};
573 * Serialize the given DOM Node to an XML string
574 * @param oNode the DOM Node to serialize
576 XMLSerializer
.prototype.serializeToString = function(oNode
) {
582 * Strips tags from the given markup string. If the given string is
583 * <code>undefined</code>, <code>null</code> or empty, it is returned as is.
586 Sarissa
.stripTags = function (s
) {
587 return s
?s
.replace(/<[^>]+>/g,""):s
;
590 * <p>Deletes all child nodes of the given node</p>
592 * @argument oNode the Node to empty
594 Sarissa
.clearChildNodes = function(oNode
) {
595 // need to check for firstChild due to opera 8 bug with hasChildNodes
596 while(oNode
.firstChild
) {
597 oNode
.removeChild(oNode
.firstChild
);
601 * <p> Copies the childNodes of nodeFrom to nodeTo</p>
602 * <p> <b>Note:</b> The second object's original content is deleted before
603 * the copy operation, unless you supply a true third parameter</p>
605 * @argument nodeFrom the Node to copy the childNodes from
606 * @argument nodeTo the Node to copy the childNodes to
607 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
609 Sarissa
.copyChildNodes = function(nodeFrom
, nodeTo
, bPreserveExisting
) {
610 if(Sarissa
._SARISSA_IS_SAFARI
&& nodeTo
.nodeType
== Node
.DOCUMENT_NODE
){ // SAFARI_OLD ??
611 nodeTo
= nodeTo
.documentElement
; //Apparently there's a bug in safari where you can't appendChild to a document node
614 if((!nodeFrom
) || (!nodeTo
)){
615 throw "Both source and destination nodes must be provided";
617 if(!bPreserveExisting
){
618 Sarissa
.clearChildNodes(nodeTo
);
620 var ownerDoc
= nodeTo
.nodeType
== Node
.DOCUMENT_NODE
? nodeTo
: nodeTo
.ownerDocument
;
621 var nodes
= nodeFrom
.childNodes
;
623 if(typeof(ownerDoc
.importNode
) != "undefined") {
624 for(i
=0;i
< nodes
.length
;i
++) {
625 nodeTo
.appendChild(ownerDoc
.importNode(nodes
[i
], true));
628 for(i
=0;i
< nodes
.length
;i
++) {
629 nodeTo
.appendChild(nodes
[i
].cloneNode(true));
635 * <p> Moves the childNodes of nodeFrom to nodeTo</p>
636 * <p> <b>Note:</b> The second object's original content is deleted before
637 * the move operation, unless you supply a true third parameter</p>
639 * @argument nodeFrom the Node to copy the childNodes from
640 * @argument nodeTo the Node to copy the childNodes to
641 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is
643 Sarissa
.moveChildNodes = function(nodeFrom
, nodeTo
, bPreserveExisting
) {
644 if((!nodeFrom
) || (!nodeTo
)){
645 throw "Both source and destination nodes must be provided";
647 if(!bPreserveExisting
){
648 Sarissa
.clearChildNodes(nodeTo
);
650 var nodes
= nodeFrom
.childNodes
;
651 // if within the same doc, just move, else copy and delete
652 if(nodeFrom
.ownerDocument
== nodeTo
.ownerDocument
){
653 while(nodeFrom
.firstChild
){
654 nodeTo
.appendChild(nodeFrom
.firstChild
);
657 var ownerDoc
= nodeTo
.nodeType
== Node
.DOCUMENT_NODE
? nodeTo
: nodeTo
.ownerDocument
;
659 if(typeof(ownerDoc
.importNode
) != "undefined") {
660 for(i
=0;i
< nodes
.length
;i
++) {
661 nodeTo
.appendChild(ownerDoc
.importNode(nodes
[i
], true));
664 for(i
=0;i
< nodes
.length
;i
++) {
665 nodeTo
.appendChild(nodes
[i
].cloneNode(true));
668 Sarissa
.clearChildNodes(nodeFrom
);
673 * <p>Serialize any <strong>non</strong> DOM object to an XML string. All properties are serialized using the property name
674 * as the XML element name. Array elements are rendered as <code>array-item</code> elements,
675 * using their index/key as the value of the <code>key</code> attribute.</p>
677 * @argument anyObject the object to serialize
678 * @argument objectName a name for that object
679 * @return the XML serialization of the given object as a string
681 Sarissa
.xmlize = function(anyObject
, objectName
, indentSpace
){
682 indentSpace
= indentSpace
?indentSpace
:'';
683 var s
= indentSpace
+ '<' + objectName
+ '>';
685 if(!(anyObject
instanceof Object
) || anyObject
instanceof Number
|| anyObject
instanceof String
|| anyObject
instanceof Boolean
|| anyObject
instanceof Date
){
686 s
+= Sarissa
.escape(""+anyObject
);
690 var isArrayItem
= anyObject
instanceof Array
;
691 for(var name
in anyObject
){
692 s
+= Sarissa
.xmlize(anyObject
[name
], (isArrayItem
?"array-item key=\""+name
+"\"":name
), indentSpace
+ " ");
696 return (s
+= (objectName
.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName
+ ">\n"));
700 * Escape the given string chacters that correspond to the five predefined XML entities
702 * @param sXml the string to escape
704 Sarissa
.escape = function(sXml
){
705 return sXml
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, ""
;").replace(/'/g, "&apos
;");
709 * Unescape the given string. This turns the occurences of the predefined XML
710 * entities to become the characters they represent correspond to the five predefined XML entities
712 * @param sXml the string to unescape
714 Sarissa.unescape = function(sXml){
715 return sXml.replace(/'/g,"'").replace(/"/g,"\"").replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&");
719 Sarissa.updateCursor = function(oTargetElement, sValue) {
720 if(oTargetElement && oTargetElement.style && oTargetElement.style.cursor != undefined ){
721 oTargetElement.style.cursor = sValue;
726 * Asynchronously update an element with response of a GET request on the given URL. Passing a configured XSLT
727 * processor will result in transforming and updating oNode before using it to update oTargetElement.
728 * You can also pass a callback function to be executed when the update is finished. The function will be called as
729 * <code>functionName(oNode, oTargetElement);</code>
731 * @param sFromUrl the URL to make the request to
732 * @param oTargetElement the element to update
733 * @param xsltproc (optional) the transformer to use on the returned
734 * content before updating the target element with it
735 * @param callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(sFromUrl, oTargetElement)</code>.
736 * In case an exception is thrown during execution, the callback is called as called as <code>callback(sFromUrl, oTargetElement, oException)</code>
737 * @param skipCache (optional) whether to skip any cache
739 Sarissa.updateContentFromURI = function(sFromUrl, oTargetElement, xsltproc, callback, skipCache) {
741 Sarissa.updateCursor(oTargetElement, "wait");
742 var xmlhttp = new XMLHttpRequest();
743 xmlhttp.open("GET", sFromUrl, true);
744 xmlhttp.onreadystatechange = function() {
745 if (xmlhttp.readyState == 4) {
747 var oDomDoc = xmlhttp.responseXML;
748 if(oDomDoc && Sarissa.getParseErrorText(oDomDoc) == Sarissa.PARSED_OK){
749 Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc);
750 callback(sFromUrl, oTargetElement);
753 throw Sarissa.getParseErrorText(oDomDoc);
758 callback(sFromUrl, oTargetElement, e);
767 var oldage = "Sat, 1 Jan 2000 00:00:00 GMT";
768 xmlhttp.setRequestHeader("If-Modified-Since", oldage);
773 Sarissa.updateCursor(oTargetElement, "auto");
775 callback(sFromUrl, oTargetElement, e);
784 * Update an element's content
with the given DOM node
. Passing a configured XSLT
785 * processor will result
in transforming and updating oNode before using it to update oTargetElement
.
786 * You can also pass a callback
function to be executed when the update is finished
. The
function will be called as
787 * <code
>functionName(oNode
, oTargetElement
);</code
>
789 * @param oNode the URL to make the request to
790 * @param oTargetElement the element to update
791 * @param
xsltproc (optional
) the transformer to
use on the given
792 * DOM node before updating the target element
with it
794 Sarissa
.updateContentFromNode = function(oNode
, oTargetElement
, xsltproc
) {
796 Sarissa
.updateCursor(oTargetElement
, "wait");
797 Sarissa
.clearChildNodes(oTargetElement
);
798 // check for parsing errors
799 var ownerDoc
= oNode
.nodeType
== Node
.DOCUMENT_NODE
?oNode
:oNode
.ownerDocument
;
800 if(ownerDoc
.parseError
&& ownerDoc
.parseError
.errorCode
!= 0) {
801 var pre
= document
.createElement("pre");
802 pre
.appendChild(document
.createTextNode(Sarissa
.getParseErrorText(ownerDoc
)));
803 oTargetElement
.appendChild(pre
);
806 // transform if appropriate
808 oNode
= xsltproc
.transformToDocument(oNode
);
810 // be smart, maybe the user wants to display the source instead
811 if(oTargetElement
.tagName
.toLowerCase() == "textarea" || oTargetElement
.tagName
.toLowerCase() == "input") {
812 oTargetElement
.value
= new XMLSerializer().serializeToString(oNode
);
815 // ok that was not smart; it was paranoid. Keep up the good work by trying to use DOM instead of innerHTML
816 if(oNode
.nodeType
== Node
.DOCUMENT_NODE
|| oNode
.ownerDocument
.documentElement
== oNode
) {
817 oTargetElement
.innerHTML
= new XMLSerializer().serializeToString(oNode
);
820 oTargetElement
.appendChild(oTargetElement
.ownerDocument
.importNode(oNode
, true));
829 Sarissa
.updateCursor(oTargetElement
, "auto");
835 * Creates an HTTP URL query string from the given HTML form data
838 Sarissa
.formToQueryString = function(oForm
){
840 for(var i
= 0;i
< oForm
.elements
.length
;i
++) {
841 var oField
= oForm
.elements
[i
];
842 var sFieldName
= oField
.getAttribute("name") ? oField
.getAttribute("name") : oField
.getAttribute("id");
843 // ensure we got a proper name/id and that the field is not disabled
845 ((!oField
.disabled
) || oField
.type
== "hidden")) {
846 switch(oField
.type
) {
851 qs
+= sFieldName
+ "=" + encodeURIComponent(oField
.value
) + "&";
854 qs
+= sFieldName
+ "=" + encodeURIComponent(oField
.options
[oField
.selectedIndex
].value
) + "&";
856 case "select-multiple":
857 for (var j
= 0; j
< oField
.length
; j
++) {
858 var optElem
= oField
.options
[j
];
859 if (optElem
.selected
=== true) {
860 qs
+= sFieldName
+ "[]" + "=" + encodeURIComponent(optElem
.value
) + "&";
867 qs
+= sFieldName
+ "=" + encodeURIComponent(oField
.value
) + "&";
873 // return after removing last '&'
874 return qs
.substr(0, qs
.length
- 1);
879 * Asynchronously update an element with response of an XMLHttpRequest-based emulation of a form submission. <p>The form <code>action</code> and
880 * <code>method</code> attributess will be followed. Passing a configured XSLT processor will result in
881 * transforming and updating the server response before using it to update the target element.
882 * You can also pass a callback function to be executed when the update is finished. The function will be called as
883 * <code>functionName(oNode, oTargetElement);</code></p>
884 * <p>Here is an example of using this in a form element:</p>
885 * <pre name="code" class="xml">
886 * <div id="targetId"> this content will be updated</div>
887 * <form action="/my/form/handler" method="post"
888 * onbeforesubmit="return Sarissa.updateContentFromForm(this, document.getElementById('targetId'));"><pre>
889 * <p>If JavaScript is supported, the form will not be submitted. Instead, Sarissa will
890 * scan the form and make an appropriate AJAX request, also adding a parameter
891 * to signal to the server that this is an AJAX call. The parameter is
892 * constructed as <code>Sarissa.REMOTE_CALL_FLAG = "=true"</code> so you can change the name in your webpage
893 * simply by assigning another value to Sarissa.REMOTE_CALL_FLAG. If JavaScript is not supported
894 * the form will be submitted normally.
896 * @param oForm the form submition to emulate
897 * @param oTargetElement the element to update
898 * @param xsltproc (optional) the transformer to use on the returned
899 * content before updating the target element with it
900 * @param callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(oNode, oTargetElement)</code>.
901 * In case an exception occurs during excecution and a callback function was provided, the exception is cought and the callback is called as
902 * <code>callback(oForm, oTargetElement, exception)</code>
904 Sarissa
.updateContentFromForm = function(oForm
, oTargetElement
, xsltproc
, callback
) {
906 Sarissa
.updateCursor(oTargetElement
, "wait");
907 // build parameters from form fields
908 var params
= Sarissa
.formToQueryString(oForm
) + "&" + Sarissa
.REMOTE_CALL_FLAG
+ "=true";
909 var xmlhttp
= new XMLHttpRequest();
910 var bUseGet
= oForm
.getAttribute("method") && oForm
.getAttribute("method").toLowerCase() == "get";
912 xmlhttp
.open("GET", oForm
.getAttribute("action")+"?"+params
, true);
915 xmlhttp
.open('POST', oForm
.getAttribute("action"), true);
916 xmlhttp
.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
917 xmlhttp
.setRequestHeader("Content-length", params
.length
);
918 xmlhttp
.setRequestHeader("Connection", "close");
920 xmlhttp
.onreadystatechange = function() {
922 if (xmlhttp
.readyState
== 4) {
923 var oDomDoc
= xmlhttp
.responseXML
;
924 if(oDomDoc
&& Sarissa
.getParseErrorText(oDomDoc
) == Sarissa
.PARSED_OK
){
925 Sarissa
.updateContentFromNode(xmlhttp
.responseXML
, oTargetElement
, xsltproc
);
926 callback(oForm
, oTargetElement
);
929 throw Sarissa
.getParseErrorText(oDomDoc
);
935 callback(oForm
, oTargetElement
, e
);
942 xmlhttp
.send(bUseGet
?"":params
);
945 Sarissa
.updateCursor(oTargetElement
, "auto");
947 callback(oForm
, oTargetElement
, e
);