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;
204 if (data.getElementsByTagName("keepAlive").length > 0) {
205 context.keepAlive = data.getElementsByTagName("keepAlive")[0].childNodes[0].nodeValue;
214 if ( context.initCallback )
215 context.initCallback();
218 context.throwError('Init failed. Malformed WS resonse.',
222 // when through proxy no need to init
224 this.initStatusOK = true;
227 // no need to ping explicitly
230 // pinging only makes sense when using pazpar2 directly
231 if( !this.initStatusOK || !this.useSessions )
233 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
237 clearTimeout(context.pingTimer);
239 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
241 { "command": "ping", "session": this.sessionID, "windowid" : window.name },
243 if ( data.getElementsByTagName("status")[0]
244 .childNodes[0].nodeValue == "OK" ) {
245 context.pingStatusOK = true;
255 context.throwError('Ping failed. Malformed WS resonse.',
260 search: function (query, num, sort, filter, showfrom, addParamsArr)
262 clearTimeout(this.statTimer);
263 clearTimeout(this.showTimer);
264 clearTimeout(this.termTimer);
265 clearTimeout(this.bytargetTimer);
267 this.showCounter = 0;
268 this.termCounter = 0;
269 this.bytargetCounter = 0;
270 this.statCounter = 0;
271 this.activeClients = 1;
274 if( !this.initStatusOK )
275 throw new Error('Pz2.js: session not initialized.');
277 if( query !== undefined )
278 this.currQuery = query;
280 throw new Error("Pz2.js: no query supplied to the search command.");
282 if ( showfrom !== undefined )
283 var start = showfrom;
289 "query": this.currQuery,
290 "session": this.sessionID,
291 "windowid" : window.name
294 if (filter !== undefined)
295 searchParams["filter"] = filter;
297 // copy additional parmeters, do not overwrite
298 if (addParamsArr != undefined) {
299 for (var prop in addParamsArr) {
300 if (!searchParams.hasOwnProperty(prop))
301 searchParams[prop] = addParamsArr[prop];
306 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
310 if ( data.getElementsByTagName("status")[0]
311 .childNodes[0].nodeValue == "OK" ) {
312 context.searchStatusOK = true;
314 context.show(start, num, sort);
315 if (context.statCallback)
317 if (context.termlistCallback)
319 if (context.bytargetCallback)
323 context.throwError('Search failed. Malformed WS resonse.',
330 if( !this.initStatusOK )
331 throw new Error('Pz2.js: session not initialized.');
333 // if called explicitly takes precedence
334 clearTimeout(this.statTimer);
337 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
339 { "command": "stat", "session": this.sessionID, "windowid" : window.name },
341 if ( data.getElementsByTagName("stat") ) {
343 Number( data.getElementsByTagName("activeclients")[0]
344 .childNodes[0].nodeValue );
345 context.activeClients = activeClients;
347 var stat = Element_parseChildNodes(data.documentElement);
349 context.statCounter++;
350 var delay = context.statTime
351 + context.statCounter * context.dumpFactor;
353 if ( activeClients > 0 )
361 context.statCallback(stat);
364 context.throwError('Stat failed. Malformed WS resonse.',
369 show: function(start, num, sort, query_state)
371 if( !this.searchStatusOK && this.useSessions )
373 'Pz2.js: show command has to be preceded with a search command.'
376 // if called explicitly takes precedence
377 clearTimeout(this.showTimer);
379 if( sort !== undefined )
380 this.currentSort = sort;
381 if( start !== undefined )
382 this.currentStart = Number( start );
383 if( num !== undefined )
384 this.currentNum = Number( num );
387 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
388 var requestParameters =
391 "session": this.sessionID,
392 "start": this.currentStart,
393 "num": this.currentNum,
394 "sort": this.currentSort,
396 "type": this.showResponseType,
397 "windowid" : window.name
400 requestParameters["query-state"] = query_state;
401 if (this.version && this.version > 0)
402 requestParameters["version"] = this.version;
405 function(data, type) {
407 var activeClients = 0;
408 if (type === "json") {
410 activeClients = Number(data.activeclients[0]);
411 show.activeclients = activeClients;
412 show.merged = Number(data.merged[0]);
413 show.total = Number(data.total[0]);
414 show.start = Number(data.start[0]);
415 show.num = Number(data.num[0]);
416 show.hits = data.hit;
417 } else if (data.getElementsByTagName("status")[0]
418 .childNodes[0].nodeValue == "OK") {
419 // first parse the status data send along with records
420 // this is strictly bound to the format
422 Number(data.getElementsByTagName("activeclients")[0]
423 .childNodes[0].nodeValue);
425 "activeclients": activeClients,
427 Number( data.getElementsByTagName("merged")[0]
428 .childNodes[0].nodeValue ),
430 Number( data.getElementsByTagName("total")[0]
431 .childNodes[0].nodeValue ),
433 Number( data.getElementsByTagName("start")[0]
434 .childNodes[0].nodeValue ),
436 Number( data.getElementsByTagName("num")[0]
437 .childNodes[0].nodeValue ),
440 // parse all the first-level nodes for all <hit> tags
441 var hits = data.getElementsByTagName("hit");
442 for (i = 0; i < hits.length; i++)
443 show.hits[i] = Element_parseChildNodes(hits[i]);
445 context.throwError('Show failed. Malformed WS resonse.',
449 var approxNode = data.getElementsByTagName("approximation");
450 if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
451 show['approximation'] =
452 Number( approxNode[0].childNodes[0].nodeValue);
455 data.getElementsByTagName("")
456 context.activeClients = activeClients;
457 context.showCounter++;
458 var delay = context.showTime;
459 if (context.showCounter > context.showFastCount)
460 delay += context.showCounter * context.dumpFactor;
461 if ( activeClients > 0 )
462 context.showTimer = setTimeout(
467 context.showCallback(show);
471 record: function(id, offset, syntax, handler)
473 // we may call record with no previous search if in proxy mode
474 if(!this.searchStatusOK && this.useSessions)
476 'Pz2.js: record command has to be preceded with a search command.'
479 if( id !== undefined )
484 "session": this.sessionID,
485 "id": this.currRecID,
486 "windowid" : window.name
489 this.currRecOffset = null;
490 if (offset != undefined) {
491 recordParams["offset"] = offset;
492 this.currRecOffset = offset;
495 if (syntax != undefined)
496 recordParams['syntax'] = syntax;
498 //overwrite default callback id needed
499 var callback = this.recordCallback;
500 var args = undefined;
501 if (handler != undefined) {
502 callback = handler['callback'];
503 args = handler['args'];
507 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
515 if (context.currRecOffset !== null) {
516 record = new Array();
517 record['xmlDoc'] = data;
518 record['offset'] = context.currRecOffset;
519 callback(record, args);
521 } else if ( recordNode =
522 data.getElementsByTagName("record")[0] ) {
523 // if stylesheet was fetched do not parse the response
524 if ( context.xslDoc ) {
525 record = new Array();
526 record['xmlDoc'] = data;
527 record['xslDoc'] = context.xslDoc;
529 recordNode.getElementsByTagName("recid")[0]
530 .firstChild.nodeValue;
533 record = Element_parseChildNodes(recordNode);
536 Number( data.getElementsByTagName("activeclients")[0]
537 .childNodes[0].nodeValue );
538 context.activeClients = activeClients;
539 context.recordCounter++;
540 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
541 if ( activeClients > 0 )
542 context.recordTimer =
545 context.record(id, offset, syntax, handler);
549 callback(record, args);
552 context.throwError('Record failed. Malformed WS resonse.',
560 if( !this.searchStatusOK && this.useSessions )
562 'Pz2.js: termlist command has to be preceded with a search command.'
565 // if called explicitly takes precedence
566 clearTimeout(this.termTimer);
569 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
572 "command": "termlist",
573 "session": this.sessionID,
574 "name": this.termKeys,
575 "windowid" : window.name,
576 "version" : this.version
580 if ( data.getElementsByTagName("termlist") ) {
582 Number( data.getElementsByTagName("activeclients")[0]
583 .childNodes[0].nodeValue );
584 context.activeClients = activeClients;
585 var termList = { "activeclients": activeClients };
586 var termLists = data.getElementsByTagName("list");
588 for (i = 0; i < termLists.length; i++) {
589 var listName = termLists[i].getAttribute('name');
590 termList[listName] = new Array();
591 var terms = termLists[i].getElementsByTagName('term');
592 //for each term in the list
593 for (j = 0; j < terms.length; j++) {
596 (terms[j].getElementsByTagName("name")[0]
598 ? terms[j].getElementsByTagName("name")[0]
599 .childNodes[0].nodeValue
603 .getElementsByTagName("frequency")[0]
604 .childNodes[0].nodeValue || 'ERROR'
607 // Only for xtargets: id, records, filtered
609 terms[j].getElementsByTagName("id");
610 if(terms[j].getElementsByTagName("id").length)
612 termIdNode[0].childNodes[0].nodeValue;
613 termList[listName][j] = term;
615 var recordsNode = terms[j].getElementsByTagName("records");
616 if (recordsNode && recordsNode.length)
617 term["records"] = recordsNode[0].childNodes[0].nodeValue;
619 var filteredNode = terms[j].getElementsByTagName("filtered");
620 if (filteredNode && filteredNode.length)
621 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
626 context.termCounter++;
627 var delay = context.termTime
628 + context.termCounter * context.dumpFactor;
629 if ( activeClients > 0 )
638 context.termlistCallback(termList);
641 context.throwError('Termlist failed. Malformed WS resonse.',
649 if( !this.initStatusOK && this.useSessions )
651 'Pz2.js: bytarget command has to be preceded with a search command.'
654 // no need to continue
655 if( !this.searchStatusOK )
658 // if called explicitly takes precedence
659 clearTimeout(this.bytargetTimer);
662 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
665 "command": "bytarget",
666 "session": this.sessionID,
668 "windowid" : window.name,
669 "version" : this.version
672 if ( data.getElementsByTagName("status")[0]
673 .childNodes[0].nodeValue == "OK" ) {
674 var targetNodes = data.getElementsByTagName("target");
675 var bytarget = new Array();
676 for ( i = 0; i < targetNodes.length; i++) {
677 bytarget[i] = new Array();
678 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
679 if ( targetNodes[i].childNodes[j].nodeType
680 == Node.ELEMENT_NODE ) {
682 targetNodes[i].childNodes[j].nodeName;
683 if (targetNodes[i].childNodes[j].firstChild != null)
685 var nodeText = targetNodes[i].childNodes[j]
686 .firstChild.nodeValue;
687 bytarget[i][nodeName] = nodeText;
690 bytarget[i][nodeName] = "";
696 if (bytarget[i]["state"]=="Client_Disconnected") {
697 bytarget[i]["hits"] = "Error";
698 } else if (bytarget[i]["state"]=="Client_Error") {
699 bytarget[i]["hits"] = "Error";
700 } else if (bytarget[i]["state"]=="Client_Working") {
701 bytarget[i]["hits"] = "...";
703 if (bytarget[i].diagnostic == "1") {
704 bytarget[i].diagnostic = "Permanent system error";
705 } else if (bytarget[i].diagnostic == "2") {
706 bytarget[i].diagnostic = "Temporary system error";
708 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
709 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
710 var suggestions = targetsSuggestions[0];
711 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
715 context.bytargetCounter++;
716 var delay = context.bytargetTime
717 + context.bytargetCounter * context.dumpFactor;
718 if ( context.activeClients > 0 )
719 context.bytargetTimer =
727 context.bytargetCallback(bytarget);
730 context.throwError('Bytarget failed. Malformed WS resonse.',
736 // just for testing, probably shouldn't be here
737 showNext: function(page)
739 var step = page || 1;
740 this.show( ( step * this.currentNum ) + this.currentStart );
743 showPrev: function(page)
745 if (this.currentStart == 0 )
747 var step = page || 1;
748 var newStart = this.currentStart - (step * this.currentNum );
749 this.show( newStart > 0 ? newStart : 0 );
752 showPage: function(pageNum)
754 //var page = pageNum || 1;
755 this.show(pageNum * this.currentNum);
760 ********************************************************************************
761 ** AJAX HELPER CLASS ***********************************************************
762 ********************************************************************************
764 var pzHttpRequest = function ( url, errorHandler ) {
765 this.maxUrlLength = 2048;
768 this.errorHandler = errorHandler || null;
770 this.requestHeaders = {};
772 if ( window.XMLHttpRequest ) {
773 this.request = new XMLHttpRequest();
774 } else if ( window.ActiveXObject ) {
776 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
778 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
784 pzHttpRequest.prototype =
786 safeGet: function ( params, callback )
788 var encodedParams = this.encodeParams(params);
789 var url = this._urlAppendParams(encodedParams);
790 if (url.length >= this.maxUrlLength) {
791 this.requestHeaders["Content-Type"]
792 = "application/x-www-form-urlencoded";
793 this._send( 'POST', this.url, encodedParams, callback );
795 this._send( 'GET', url, '', callback );
799 get: function ( params, callback )
801 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
805 post: function ( params, data, callback )
807 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
814 this.request.open( 'GET', this.url, this.async );
815 this.request.send('');
816 if ( this.request.status == 200 )
817 return this.request.responseXML;
820 encodeParams: function (params)
824 for (var key in params) {
825 if (params[key] != null) {
826 encoded += sep + key + '=' + encodeURIComponent(params[key]);
833 _send: function ( type, url, data, callback)
836 this.callback = callback;
838 this.request.open( type, url, this.async );
839 for (var key in this.requestHeaders)
840 this.request.setRequestHeader(key, this.requestHeaders[key]);
841 this.request.onreadystatechange = function () {
842 context._handleResponse(url); /// url used ONLY for error reporting
844 this.request.send(data);
847 _urlAppendParams: function (encodedParams)
850 return this.url + "?" + encodedParams;
855 _handleResponse: function (savedUrlForErrorReporting)
857 if ( this.request.readyState == 4 ) {
858 // pick up appplication errors first
860 if (this.request.responseXML &&
861 (errNode = this.request.responseXML.documentElement)
862 && errNode.nodeName == 'error') {
863 var errMsg = errNode.getAttribute("msg");
864 var errCode = errNode.getAttribute("code");
866 if (errNode.childNodes.length)
867 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
869 var err = new Error(errMsg + errAddInfo);
872 if (this.errorHandler) {
873 this.errorHandler(err);
878 } else if (this.request.status == 200 &&
879 this.request.responseXML == null) {
880 if (this.request.responseText != null) {
884 var text = this.request.responseText;
885 if (typeof window.JSON == "undefined")
886 json = eval("(" + text + ")");
889 json = JSON.parse(text);
892 // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
893 /* DEBUG only works in mk2-mobile
894 if (document.getElementById("log"))
895 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
898 json = eval("(" + text + ")");
901 /* DEBUG only works in mk2-mobile
902 if (document.getElementById("log"))
903 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
908 this.callback(json, "json");
910 var err = new Error("XML response is empty but no error " +
911 "for " + savedUrlForErrorReporting);
913 if (this.errorHandler) {
914 this.errorHandler(err);
919 } else if (this.request.status == 200) {
920 this.callback(this.request.responseXML);
922 var err = new Error("HTTP response not OK: "
923 + this.request.status + " - "
924 + this.request.statusText );
925 err.code = '00' + this.request.status;
926 if (this.errorHandler) {
927 this.errorHandler(err);
938 ********************************************************************************
939 ** XML HELPER FUNCTIONS ********************************************************
940 ********************************************************************************
945 if ( window.ActiveXObject) {
946 var DOMDoc = document;
948 var DOMDoc = Document.prototype;
951 DOMDoc.newXmlDoc = function ( root )
955 if (document.implementation && document.implementation.createDocument) {
956 doc = document.implementation.createDocument('', root, null);
957 } else if ( window.ActiveXObject ) {
958 doc = new ActiveXObject("MSXML2.DOMDocument");
959 doc.loadXML('<' + root + '/>');
961 throw new Error ('No XML support in this browser');
968 DOMDoc.parseXmlFromString = function ( xmlString )
972 if ( window.DOMParser ) {
973 var parser = new DOMParser();
974 doc = parser.parseFromString( xmlString, "text/xml");
975 } else if ( window.ActiveXObject ) {
976 doc = new ActiveXObject("MSXML2.DOMDocument");
977 doc.loadXML( xmlString );
979 throw new Error ("No XML parsing support in this browser.");
985 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
987 if ( window.XSLTProcessor ) {
988 var proc = new XSLTProcessor();
989 proc.importStylesheet( xslDoc );
990 return proc.transformToDocument(xmlDoc);
991 } else if ( window.ActiveXObject ) {
992 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
994 alert( 'Unable to perform XSLT transformation in this browser' );
1000 Element_removeFromDoc = function (DOM_Element)
1002 DOM_Element.parentNode.removeChild(DOM_Element);
1005 Element_emptyChildren = function (DOM_Element)
1007 while( DOM_Element.firstChild ) {
1008 DOM_Element.removeChild( DOM_Element.firstChild )
1012 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1014 if ( window.XSLTProcessor ) {
1015 var proc = new XSLTProcessor();
1016 proc.importStylesheet( xslDoc );
1017 var docFrag = false;
1018 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1019 DOM_Element.appendChild(docFrag);
1020 } else if ( window.ActiveXObject ) {
1021 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1023 alert( 'Unable to perform XSLT transformation in this browser' );
1027 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1029 var node = DOM_Element.ownerDocument.createElement(tagName);
1030 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1032 DOM_Element.appendChild(node);
1033 node.appendChild(text);
1038 Element_setTextContent = function ( DOM_Element, textContent )
1040 if (typeof DOM_Element.textContent !== "undefined") {
1041 DOM_Element.textContent = textContent;
1042 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1043 DOM_Element.innerText = textContent;
1045 throw new Error("Cannot set text content of the node, no such method.");
1049 Element_getTextContent = function (DOM_Element)
1051 if ( typeof DOM_Element.textContent != 'undefined' ) {
1052 return DOM_Element.textContent;
1053 } else if (typeof DOM_Element.text != 'undefined') {
1054 return DOM_Element.text;
1056 throw new Error("Cannot get text content of the node, no such method.");
1060 Element_parseChildNodes = function (node)
1063 var hasChildElems = false;
1065 if (node.hasChildNodes()) {
1066 var children = node.childNodes;
1067 for (var i = 0; i < children.length; i++) {
1068 var child = children[i];
1069 if (child.nodeType == Node.ELEMENT_NODE) {
1070 hasChildElems = true;
1071 var nodeName = child.nodeName;
1072 if (!(nodeName in parsed))
1073 parsed[nodeName] = [];
1074 parsed[nodeName].push(Element_parseChildNodes(child));
1079 var attrs = node.attributes;
1080 for (var i = 0; i < attrs.length; i++) {
1081 var attrName = '@' + attrs[i].nodeName;
1082 var attrValue = attrs[i].nodeValue;
1083 parsed[attrName] = attrValue;
1086 // if no nested elements, get text content
1087 if (node.hasChildNodes() && !hasChildElems) {
1088 if (node.attributes.length)
1089 parsed['#text'] = node.firstChild.nodeValue;
1091 parsed = node.firstChild.nodeValue;
1097 /* do not remove trailing bracket */