3 ** pz2.js - pazpar2's javascript client library.
6 //since explorer is flawed
8 window.Node = new Object();
10 Node.ATTRIBUTE_NODE = 2;
12 Node.CDATA_SECTION_NODE = 4;
13 Node.ENTITY_REFERENCE_NODE = 5;
15 Node.PROCESSING_INSTRUCTION_NODE = 7;
16 Node.COMMENT_NODE = 8;
17 Node.DOCUMENT_NODE = 9;
18 Node.DOCUMENT_TYPE_NODE = 10;
19 Node.DOCUMENT_FRAGMENT_NODE = 11;
20 Node.NOTATION_NODE = 12;
23 // prevent execution of more than once
24 if(typeof window.pz2 == "undefined") {
25 window.undefined = window.undefined;
27 var pz2 = function ( paramArray )
30 // at least one callback required
32 throw new Error("Pz2.js: Array with parameters has to be suplied.");
34 //supported pazpar2's protocol version
35 this.suppProtoVer = '1';
36 if (typeof paramArray.pazpar2path != "undefined")
37 this.pz2String = paramArray.pazpar2path;
39 this.pz2String = "/pazpar2/search.pz2";
40 this.useSessions = true;
42 this.stylesheet = paramArray.detailstylesheet || null;
43 //load stylesheet if required in async mode
44 if( this.stylesheet ) {
46 var request = new pzHttpRequest( this.stylesheet );
47 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
50 this.errorHandler = paramArray.errorhandler || null;
51 this.showResponseType = paramArray.showResponseType || "xml";
54 this.initCallback = paramArray.oninit || null;
55 this.statCallback = paramArray.onstat || null;
56 this.showCallback = paramArray.onshow || null;
57 this.termlistCallback = paramArray.onterm || null;
58 this.recordCallback = paramArray.onrecord || null;
59 this.bytargetCallback = paramArray.onbytarget || null;
60 this.resetCallback = paramArray.onreset || null;
63 this.termKeys = paramArray.termlist || "subject";
65 // some configurational stuff
66 this.keepAlive = 50000;
68 if ( paramArray.keepAlive < this.keepAlive )
69 this.keepAlive = paramArray.keepAlive;
71 this.sessionID = null;
72 this.serviceId = paramArray.serviceId || null;
73 this.initStatusOK = false;
74 this.pingStatusOK = false;
75 this.searchStatusOK = false;
78 this.currentSort = "relevance";
81 this.currentStart = 0;
82 // currentNum can be overwritten in show
85 // last full record retrieved
86 this.currRecID = null;
89 this.currQuery = null;
91 //current raw record offset
92 this.currRecOffset = null;
95 this.pingTimer = null;
96 this.statTime = paramArray.stattime || 1000;
97 this.statTimer = null;
98 this.termTime = paramArray.termtime || 1000;
99 this.termTimer = null;
100 this.showTime = paramArray.showtime || 1000;
101 this.showTimer = null;
102 this.showFastCount = 4;
103 this.bytargetTime = paramArray.bytargettime || 1000;
104 this.bytargetTimer = null;
105 this.recordTime = paramArray.recordtime || 500;
106 this.recordTimer = null;
108 // counters for each command and applied delay
109 this.dumpFactor = 500;
110 this.showCounter = 0;
111 this.termCounter = 0;
112 this.statCounter = 0;
113 this.bytargetCounter = 0;
114 this.recordCounter = 0;
116 // active clients, updated by stat and show
117 // might be an issue since bytarget will poll accordingly
118 this.activeClients = 1;
120 // if in proxy mode no need to init
121 if (paramArray.usesessions != undefined) {
122 this.useSessions = paramArray.usesessions;
123 this.initStatusOK = true;
125 // else, auto init session or wait for a user init?
126 if (this.useSessions && paramArray.autoInit !== false) {
127 this.init(this.sessionId, this.serviceId);
130 this.version = paramArray.version || null;
135 //error handler for async error throws
136 throwError: function (errMsg, errCode)
138 var err = new Error(errMsg);
139 if (errCode) err.code = errCode;
141 if (this.errorHandler) {
142 this.errorHandler(err);
149 // stop activity by clearing tiemouts
152 clearTimeout(this.statTimer);
153 clearTimeout(this.showTimer);
154 clearTimeout(this.termTimer);
155 clearTimeout(this.bytargetTimer);
158 // reset status variables
161 if ( this.useSessions ) {
162 this.sessionID = null;
163 this.initStatusOK = false;
164 this.pingStatusOK = false;
165 clearTimeout(this.pingTimer);
167 this.searchStatusOK = false;
170 if ( this.resetCallback )
171 this.resetCallback();
174 init: function (sessionId, serviceId)
178 // session id as a param
179 if (sessionId && this.useSessions ) {
180 this.initStatusOK = true;
181 this.sessionID = sessionId;
183 // old school direct pazpar2 init
184 } else if (this.useSessions) {
186 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
187 var opts = {'command' : 'init'};
188 if (serviceId) opts.service = serviceId;
192 if ( data.getElementsByTagName("status")[0]
193 .childNodes[0].nodeValue == "OK" ) {
194 if ( data.getElementsByTagName("protocol")[0]
195 .childNodes[0].nodeValue
196 != context.suppProtoVer )
198 "Server's protocol not supported by the client"
200 context.initStatusOK = true;
202 data.getElementsByTagName("session")[0]
203 .childNodes[0].nodeValue;
211 if ( context.initCallback )
212 context.initCallback();
215 context.throwError('Init failed. Malformed WS resonse.',
219 // when through proxy no need to init
221 this.initStatusOK = true;
224 // no need to ping explicitly
227 // pinging only makes sense when using pazpar2 directly
228 if( !this.initStatusOK || !this.useSessions )
230 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
234 clearTimeout(context.pingTimer);
236 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
238 { "command": "ping", "session": this.sessionID, "windowid" : window.name },
240 if ( data.getElementsByTagName("status")[0]
241 .childNodes[0].nodeValue == "OK" ) {
242 context.pingStatusOK = true;
252 context.throwError('Ping failed. Malformed WS resonse.',
257 search: function (query, num, sort, filter, showfrom, addParamsArr)
259 clearTimeout(this.statTimer);
260 clearTimeout(this.showTimer);
261 clearTimeout(this.termTimer);
262 clearTimeout(this.bytargetTimer);
264 this.showCounter = 0;
265 this.termCounter = 0;
266 this.bytargetCounter = 0;
267 this.statCounter = 0;
268 this.activeClients = 1;
271 if( !this.initStatusOK )
272 throw new Error('Pz2.js: session not initialized.');
274 if( query !== undefined )
275 this.currQuery = query;
277 throw new Error("Pz2.js: no query supplied to the search command.");
279 if ( showfrom !== undefined )
280 var start = showfrom;
286 "query": this.currQuery,
287 "session": this.sessionID,
288 "windowid" : window.name
291 if (filter !== undefined)
292 searchParams["filter"] = filter;
294 // copy additional parmeters, do not overwrite
295 if (addParamsArr != undefined) {
296 for (var prop in addParamsArr) {
297 if (!searchParams.hasOwnProperty(prop))
298 searchParams[prop] = addParamsArr[prop];
303 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
307 if ( data.getElementsByTagName("status")[0]
308 .childNodes[0].nodeValue == "OK" ) {
309 context.searchStatusOK = true;
311 context.show(start, num, sort);
312 if (context.statCallback)
314 if (context.termlistCallback)
316 if (context.bytargetCallback)
320 context.throwError('Search failed. Malformed WS resonse.',
327 if( !this.initStatusOK )
328 throw new Error('Pz2.js: session not initialized.');
330 // if called explicitly takes precedence
331 clearTimeout(this.statTimer);
334 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
336 { "command": "stat", "session": this.sessionID, "windowid" : window.name },
338 if ( data.getElementsByTagName("stat") ) {
340 Number( data.getElementsByTagName("activeclients")[0]
341 .childNodes[0].nodeValue );
342 context.activeClients = activeClients;
344 var stat = Element_parseChildNodes(data.documentElement);
346 context.statCounter++;
347 var delay = context.statTime
348 + context.statCounter * context.dumpFactor;
350 if ( activeClients > 0 )
358 context.statCallback(stat);
361 context.throwError('Stat failed. Malformed WS resonse.',
366 show: function(start, num, sort, query_state)
368 if( !this.searchStatusOK && this.useSessions )
370 'Pz2.js: show command has to be preceded with a search command.'
373 // if called explicitly takes precedence
374 clearTimeout(this.showTimer);
376 if( sort !== undefined )
377 this.currentSort = sort;
378 if( start !== undefined )
379 this.currentStart = Number( start );
380 if( num !== undefined )
381 this.currentNum = Number( num );
384 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
385 var requestParameters =
388 "session": this.sessionID,
389 "start": this.currentStart,
390 "num": this.currentNum,
391 "sort": this.currentSort,
393 "type": this.showResponseType,
394 "windowid" : window.name,
397 requestParameters["query-state"] = query_state;
398 if (this.version && this.version > 0)
399 requestParameters["version"] = this.version;
402 function(data, type) {
404 var activeClients = 0;
405 if (type === "json") {
407 activeClients = Number(data.activeclients[0]);
408 show.activeclients = activeClients;
409 show.merged = Number(data.merged[0]);
410 show.total = Number(data.total[0]);
411 show.start = Number(data.start[0]);
412 show.num = Number(data.num[0]);
413 show.hits = data.hit;
414 } else if (data.getElementsByTagName("status")[0]
415 .childNodes[0].nodeValue == "OK") {
416 // first parse the status data send along with records
417 // this is strictly bound to the format
419 Number(data.getElementsByTagName("activeclients")[0]
420 .childNodes[0].nodeValue);
422 "activeclients": activeClients,
424 Number( data.getElementsByTagName("merged")[0]
425 .childNodes[0].nodeValue ),
427 Number( data.getElementsByTagName("total")[0]
428 .childNodes[0].nodeValue ),
430 Number( data.getElementsByTagName("start")[0]
431 .childNodes[0].nodeValue ),
433 Number( data.getElementsByTagName("num")[0]
434 .childNodes[0].nodeValue ),
437 // parse all the first-level nodes for all <hit> tags
438 var hits = data.getElementsByTagName("hit");
439 for (i = 0; i < hits.length; i++)
440 show.hits[i] = Element_parseChildNodes(hits[i]);
442 context.throwError('Show failed. Malformed WS resonse.',
445 var approxNode = data.getElementsByTagName("approximation");
447 show['approximation'] =
448 Number( approxNode[0].childNodes[0].nodeValue);
451 data.getElementsByTagName("")
452 context.activeClients = activeClients;
453 context.showCounter++;
454 var delay = context.showTime;
455 if (context.showCounter > context.showFastCount)
456 delay += context.showCounter * context.dumpFactor;
457 if ( activeClients > 0 )
458 context.showTimer = setTimeout(
463 context.showCallback(show);
467 record: function(id, offset, syntax, handler)
469 // we may call record with no previous search if in proxy mode
470 if(!this.searchStatusOK && this.useSessions)
472 'Pz2.js: record command has to be preceded with a search command.'
475 if( id !== undefined )
480 "session": this.sessionID,
481 "id": this.currRecID,
482 "windowid" : window.name
485 this.currRecOffset = null;
486 if (offset != undefined) {
487 recordParams["offset"] = offset;
488 this.currRecOffset = offset;
491 if (syntax != undefined)
492 recordParams['syntax'] = syntax;
494 //overwrite default callback id needed
495 var callback = this.recordCallback;
496 var args = undefined;
497 if (handler != undefined) {
498 callback = handler['callback'];
499 args = handler['args'];
503 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
511 if (context.currRecOffset !== null) {
512 record = new Array();
513 record['xmlDoc'] = data;
514 record['offset'] = context.currRecOffset;
515 callback(record, args);
517 } else if ( recordNode =
518 data.getElementsByTagName("record")[0] ) {
519 // if stylesheet was fetched do not parse the response
520 if ( context.xslDoc ) {
521 record = new Array();
522 record['xmlDoc'] = data;
523 record['xslDoc'] = context.xslDoc;
525 recordNode.getElementsByTagName("recid")[0]
526 .firstChild.nodeValue;
529 record = Element_parseChildNodes(recordNode);
532 Number( data.getElementsByTagName("activeclients")[0]
533 .childNodes[0].nodeValue );
534 context.activeClients = activeClients;
535 context.recordCounter++;
536 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
537 if ( activeClients > 0 )
538 context.recordTimer =
541 context.record(id, offset, syntax, handler);
545 callback(record, args);
548 context.throwError('Record failed. Malformed WS resonse.',
556 if( !this.searchStatusOK && this.useSessions )
558 'Pz2.js: termlist command has to be preceded with a search command.'
561 // if called explicitly takes precedence
562 clearTimeout(this.termTimer);
565 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
568 "command": "termlist",
569 "session": this.sessionID,
570 "name": this.termKeys,
571 "windowid" : window.name,
572 "version" : this.version
576 if ( data.getElementsByTagName("termlist") ) {
578 Number( data.getElementsByTagName("activeclients")[0]
579 .childNodes[0].nodeValue );
580 context.activeClients = activeClients;
581 var termList = { "activeclients": activeClients };
582 var termLists = data.getElementsByTagName("list");
584 for (i = 0; i < termLists.length; i++) {
585 var listName = termLists[i].getAttribute('name');
586 termList[listName] = new Array();
587 var terms = termLists[i].getElementsByTagName('term');
588 //for each term in the list
589 for (j = 0; j < terms.length; j++) {
592 (terms[j].getElementsByTagName("name")[0]
594 ? terms[j].getElementsByTagName("name")[0]
595 .childNodes[0].nodeValue
599 .getElementsByTagName("frequency")[0]
600 .childNodes[0].nodeValue || 'ERROR'
603 // Only for xtargets: id, records, filtered
605 terms[j].getElementsByTagName("id");
606 if(terms[j].getElementsByTagName("id").length)
608 termIdNode[0].childNodes[0].nodeValue;
609 termList[listName][j] = term;
611 var recordsNode = terms[j].getElementsByTagName("records");
612 if (recordsNode && recordsNode.length)
613 term["records"] = recordsNode[0].childNodes[0].nodeValue;
615 var filteredNode = terms[j].getElementsByTagName("filtered");
616 if (filteredNode && filteredNode.length)
617 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
622 context.termCounter++;
623 var delay = context.termTime
624 + context.termCounter * context.dumpFactor;
625 if ( activeClients > 0 )
634 context.termlistCallback(termList);
637 context.throwError('Termlist failed. Malformed WS resonse.',
645 if( !this.initStatusOK && this.useSessions )
647 'Pz2.js: bytarget command has to be preceded with a search command.'
650 // no need to continue
651 if( !this.searchStatusOK )
654 // if called explicitly takes precedence
655 clearTimeout(this.bytargetTimer);
658 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
661 "command": "bytarget",
662 "session": this.sessionID,
664 "windowid" : window.name,
665 "version" : this.version
668 if ( data.getElementsByTagName("status")[0]
669 .childNodes[0].nodeValue == "OK" ) {
670 var targetNodes = data.getElementsByTagName("target");
671 var bytarget = new Array();
672 for ( i = 0; i < targetNodes.length; i++) {
673 bytarget[i] = new Array();
674 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
675 if ( targetNodes[i].childNodes[j].nodeType
676 == Node.ELEMENT_NODE ) {
678 targetNodes[i].childNodes[j].nodeName;
679 if (targetNodes[i].childNodes[j].firstChild != null)
681 var nodeText = targetNodes[i].childNodes[j]
682 .firstChild.nodeValue;
683 bytarget[i][nodeName] = nodeText;
686 bytarget[i][nodeName] = "";
692 if (bytarget[i]["state"]=="Client_Disconnected") {
693 bytarget[i]["hits"] = "Error";
694 } else if (bytarget[i]["state"]=="Client_Error") {
695 bytarget[i]["hits"] = "Error";
696 } else if (bytarget[i]["state"]=="Client_Working") {
697 bytarget[i]["hits"] = "...";
699 if (bytarget[i].diagnostic == "1") {
700 bytarget[i].diagnostic = "Permanent system error";
701 } else if (bytarget[i].diagnostic == "2") {
702 bytarget[i].diagnostic = "Temporary system error";
704 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
705 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
706 var suggestions = targetsSuggestions[0];
707 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
711 context.bytargetCounter++;
712 var delay = context.bytargetTime
713 + context.bytargetCounter * context.dumpFactor;
714 if ( context.activeClients > 0 )
715 context.bytargetTimer =
723 context.bytargetCallback(bytarget);
726 context.throwError('Bytarget failed. Malformed WS resonse.',
732 // just for testing, probably shouldn't be here
733 showNext: function(page)
735 var step = page || 1;
736 this.show( ( step * this.currentNum ) + this.currentStart );
739 showPrev: function(page)
741 if (this.currentStart == 0 )
743 var step = page || 1;
744 var newStart = this.currentStart - (step * this.currentNum );
745 this.show( newStart > 0 ? newStart : 0 );
748 showPage: function(pageNum)
750 //var page = pageNum || 1;
751 this.show(pageNum * this.currentNum);
756 ********************************************************************************
757 ** AJAX HELPER CLASS ***********************************************************
758 ********************************************************************************
760 var pzHttpRequest = function ( url, errorHandler ) {
761 this.maxUrlLength = 2048;
764 this.errorHandler = errorHandler || null;
766 this.requestHeaders = {};
768 if ( window.XMLHttpRequest ) {
769 this.request = new XMLHttpRequest();
770 } else if ( window.ActiveXObject ) {
772 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
774 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
780 pzHttpRequest.prototype =
782 safeGet: function ( params, callback )
784 var encodedParams = this.encodeParams(params);
785 var url = this._urlAppendParams(encodedParams);
786 if (url.length >= this.maxUrlLength) {
787 this.requestHeaders["Content-Type"]
788 = "application/x-www-form-urlencoded";
789 this._send( 'POST', this.url, encodedParams, callback );
791 this._send( 'GET', url, '', callback );
795 get: function ( params, callback )
797 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
801 post: function ( params, data, callback )
803 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
810 this.request.open( 'GET', this.url, this.async );
811 this.request.send('');
812 if ( this.request.status == 200 )
813 return this.request.responseXML;
816 encodeParams: function (params)
820 for (var key in params) {
821 if (params[key] != null) {
822 encoded += sep + key + '=' + encodeURIComponent(params[key]);
829 _send: function ( type, url, data, callback)
832 this.callback = callback;
834 this.request.open( type, url, this.async );
835 for (var key in this.requestHeaders)
836 this.request.setRequestHeader(key, this.requestHeaders[key]);
837 this.request.onreadystatechange = function () {
838 context._handleResponse(url); /// url used ONLY for error reporting
840 this.request.send(data);
843 _urlAppendParams: function (encodedParams)
846 return this.url + "?" + encodedParams;
851 _handleResponse: function (savedUrlForErrorReporting)
853 if ( this.request.readyState == 4 ) {
854 // pick up appplication errors first
856 if (this.request.responseXML &&
857 (errNode = this.request.responseXML.documentElement)
858 && errNode.nodeName == 'error') {
859 var errMsg = errNode.getAttribute("msg");
860 var errCode = errNode.getAttribute("code");
862 if (errNode.childNodes.length)
863 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
865 var err = new Error(errMsg + errAddInfo);
868 if (this.errorHandler) {
869 this.errorHandler(err);
874 } else if (this.request.status == 200 &&
875 this.request.responseXML == null) {
876 if (this.request.responseText != null) {
880 var text = this.request.responseText;
881 if (typeof window.JSON == "undefined")
882 json = eval("(" + text + ")");
885 json = JSON.parse(text);
888 // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
889 /* DEBUG only works in mk2-mobile
890 if (document.getElementById("log"))
891 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
894 json = eval("(" + text + ")");
897 /* DEBUG only works in mk2-mobile
898 if (document.getElementById("log"))
899 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
904 this.callback(json, "json");
906 var err = new Error("XML response is empty but no error " +
907 "for " + savedUrlForErrorReporting);
909 if (this.errorHandler) {
910 this.errorHandler(err);
915 } else if (this.request.status == 200) {
916 this.callback(this.request.responseXML);
918 var err = new Error("HTTP response not OK: "
919 + this.request.status + " - "
920 + this.request.statusText );
921 err.code = '00' + this.request.status;
922 if (this.errorHandler) {
923 this.errorHandler(err);
934 ********************************************************************************
935 ** XML HELPER FUNCTIONS ********************************************************
936 ********************************************************************************
941 if ( window.ActiveXObject) {
942 var DOMDoc = document;
944 var DOMDoc = Document.prototype;
947 DOMDoc.newXmlDoc = function ( root )
951 if (document.implementation && document.implementation.createDocument) {
952 doc = document.implementation.createDocument('', root, null);
953 } else if ( window.ActiveXObject ) {
954 doc = new ActiveXObject("MSXML2.DOMDocument");
955 doc.loadXML('<' + root + '/>');
957 throw new Error ('No XML support in this browser');
964 DOMDoc.parseXmlFromString = function ( xmlString )
968 if ( window.DOMParser ) {
969 var parser = new DOMParser();
970 doc = parser.parseFromString( xmlString, "text/xml");
971 } else if ( window.ActiveXObject ) {
972 doc = new ActiveXObject("MSXML2.DOMDocument");
973 doc.loadXML( xmlString );
975 throw new Error ("No XML parsing support in this browser.");
981 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
983 if ( window.XSLTProcessor ) {
984 var proc = new XSLTProcessor();
985 proc.importStylesheet( xslDoc );
986 return proc.transformToDocument(xmlDoc);
987 } else if ( window.ActiveXObject ) {
988 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
990 alert( 'Unable to perform XSLT transformation in this browser' );
996 Element_removeFromDoc = function (DOM_Element)
998 DOM_Element.parentNode.removeChild(DOM_Element);
1001 Element_emptyChildren = function (DOM_Element)
1003 while( DOM_Element.firstChild ) {
1004 DOM_Element.removeChild( DOM_Element.firstChild )
1008 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1010 if ( window.XSLTProcessor ) {
1011 var proc = new XSLTProcessor();
1012 proc.importStylesheet( xslDoc );
1013 var docFrag = false;
1014 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1015 DOM_Element.appendChild(docFrag);
1016 } else if ( window.ActiveXObject ) {
1017 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1019 alert( 'Unable to perform XSLT transformation in this browser' );
1023 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1025 var node = DOM_Element.ownerDocument.createElement(tagName);
1026 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1028 DOM_Element.appendChild(node);
1029 node.appendChild(text);
1034 Element_setTextContent = function ( DOM_Element, textContent )
1036 if (typeof DOM_Element.textContent !== "undefined") {
1037 DOM_Element.textContent = textContent;
1038 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1039 DOM_Element.innerText = textContent;
1041 throw new Error("Cannot set text content of the node, no such method.");
1045 Element_getTextContent = function (DOM_Element)
1047 if ( typeof DOM_Element.textContent != 'undefined' ) {
1048 return DOM_Element.textContent;
1049 } else if (typeof DOM_Element.text != 'undefined') {
1050 return DOM_Element.text;
1052 throw new Error("Cannot get text content of the node, no such method.");
1056 Element_parseChildNodes = function (node)
1059 var hasChildElems = false;
1061 if (node.hasChildNodes()) {
1062 var children = node.childNodes;
1063 for (var i = 0; i < children.length; i++) {
1064 var child = children[i];
1065 if (child.nodeType == Node.ELEMENT_NODE) {
1066 hasChildElems = true;
1067 var nodeName = child.nodeName;
1068 if (!(nodeName in parsed))
1069 parsed[nodeName] = [];
1070 parsed[nodeName].push(Element_parseChildNodes(child));
1075 var attrs = node.attributes;
1076 for (var i = 0; i < attrs.length; i++) {
1077 var attrName = '@' + attrs[i].nodeName;
1078 var attrValue = attrs[i].nodeValue;
1079 parsed[attrName] = attrValue;
1082 // if no nested elements, get text content
1083 if (node.hasChildNodes() && !hasChildElems) {
1084 if (node.attributes.length)
1085 parsed['#text'] = node.firstChild.nodeValue;
1087 parsed = node.firstChild.nodeValue;
1093 /* do not remove trailing bracket */