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( sort !== undefined ) {
295 this.currentSort = sort;
296 searchParams["sort"] = sort;
298 if (filter !== undefined)
299 searchParams["filter"] = filter;
301 // copy additional parmeters, do not overwrite
302 if (addParamsArr != undefined) {
303 for (var prop in addParamsArr) {
304 if (!searchParams.hasOwnProperty(prop))
305 searchParams[prop] = addParamsArr[prop];
310 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
314 if ( data.getElementsByTagName("status")[0]
315 .childNodes[0].nodeValue == "OK" ) {
316 context.searchStatusOK = true;
318 context.show(start, num, sort);
319 if (context.statCallback)
321 if (context.termlistCallback)
323 if (context.bytargetCallback)
327 context.throwError('Search failed. Malformed WS resonse.',
334 if( !this.initStatusOK )
335 throw new Error('Pz2.js: session not initialized.');
337 // if called explicitly takes precedence
338 clearTimeout(this.statTimer);
341 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
343 { "command": "stat", "session": this.sessionID, "windowid" : window.name },
345 if ( data.getElementsByTagName("stat") ) {
347 Number( data.getElementsByTagName("activeclients")[0]
348 .childNodes[0].nodeValue );
349 context.activeClients = activeClients;
351 var stat = Element_parseChildNodes(data.documentElement);
353 context.statCounter++;
354 var delay = context.statTime
355 + context.statCounter * context.dumpFactor;
357 if ( activeClients > 0 )
365 context.statCallback(stat);
368 context.throwError('Stat failed. Malformed WS resonse.',
373 show: function(start, num, sort, query_state)
375 if( !this.searchStatusOK && this.useSessions )
377 'Pz2.js: show command has to be preceded with a search command.'
380 // if called explicitly takes precedence
381 clearTimeout(this.showTimer);
383 if( sort !== undefined )
384 this.currentSort = sort;
385 if( start !== undefined )
386 this.currentStart = Number( start );
387 if( num !== undefined )
388 this.currentNum = Number( num );
391 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
392 var requestParameters =
395 "session": this.sessionID,
396 "start": this.currentStart,
397 "num": this.currentNum,
398 "sort": this.currentSort,
400 "type": this.showResponseType,
401 "windowid" : window.name
404 requestParameters["query-state"] = query_state;
405 if (this.version && this.version > 0)
406 requestParameters["version"] = this.version;
409 function(data, type) {
411 var activeClients = 0;
412 if (type === "json") {
414 activeClients = Number(data.activeclients[0]);
415 show.activeclients = activeClients;
416 show.merged = Number(data.merged[0]);
417 show.total = Number(data.total[0]);
418 show.start = Number(data.start[0]);
419 show.num = Number(data.num[0]);
420 show.hits = data.hit;
421 } else if (data.getElementsByTagName("status")[0]
422 .childNodes[0].nodeValue == "OK") {
423 // first parse the status data send along with records
424 // this is strictly bound to the format
426 Number(data.getElementsByTagName("activeclients")[0]
427 .childNodes[0].nodeValue);
429 "activeclients": activeClients,
431 Number( data.getElementsByTagName("merged")[0]
432 .childNodes[0].nodeValue ),
434 Number( data.getElementsByTagName("total")[0]
435 .childNodes[0].nodeValue ),
437 Number( data.getElementsByTagName("start")[0]
438 .childNodes[0].nodeValue ),
440 Number( data.getElementsByTagName("num")[0]
441 .childNodes[0].nodeValue ),
444 // parse all the first-level nodes for all <hit> tags
445 var hits = data.getElementsByTagName("hit");
446 for (i = 0; i < hits.length; i++)
447 show.hits[i] = Element_parseChildNodes(hits[i]);
449 context.throwError('Show failed. Malformed WS resonse.',
453 var approxNode = data.getElementsByTagName("approximation");
454 if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
455 show['approximation'] =
456 Number( approxNode[0].childNodes[0].nodeValue);
459 data.getElementsByTagName("")
460 context.activeClients = activeClients;
461 context.showCounter++;
462 var delay = context.showTime;
463 if (context.showCounter > context.showFastCount)
464 delay += context.showCounter * context.dumpFactor;
465 if ( activeClients > 0 )
466 context.showTimer = setTimeout(
471 context.showCallback(show);
475 record: function(id, offset, syntax, handler)
477 // we may call record with no previous search if in proxy mode
478 if(!this.searchStatusOK && this.useSessions)
480 'Pz2.js: record command has to be preceded with a search command.'
483 if( id !== undefined )
488 "session": this.sessionID,
489 "id": this.currRecID,
490 "windowid" : window.name
493 this.currRecOffset = null;
494 if (offset != undefined) {
495 recordParams["offset"] = offset;
496 this.currRecOffset = offset;
499 if (syntax != undefined)
500 recordParams['syntax'] = syntax;
502 //overwrite default callback id needed
503 var callback = this.recordCallback;
504 var args = undefined;
505 if (handler != undefined) {
506 callback = handler['callback'];
507 args = handler['args'];
511 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
519 if (context.currRecOffset !== null) {
520 record = new Array();
521 record['xmlDoc'] = data;
522 record['offset'] = context.currRecOffset;
523 callback(record, args);
525 } else if ( recordNode =
526 data.getElementsByTagName("record")[0] ) {
527 // if stylesheet was fetched do not parse the response
528 if ( context.xslDoc ) {
529 record = new Array();
530 record['xmlDoc'] = data;
531 record['xslDoc'] = context.xslDoc;
533 recordNode.getElementsByTagName("recid")[0]
534 .firstChild.nodeValue;
537 record = Element_parseChildNodes(recordNode);
540 Number( data.getElementsByTagName("activeclients")[0]
541 .childNodes[0].nodeValue );
542 context.activeClients = activeClients;
543 context.recordCounter++;
544 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
545 if ( activeClients > 0 )
546 context.recordTimer =
549 context.record(id, offset, syntax, handler);
553 callback(record, args);
556 context.throwError('Record failed. Malformed WS resonse.',
564 if( !this.searchStatusOK && this.useSessions )
566 'Pz2.js: termlist command has to be preceded with a search command.'
569 // if called explicitly takes precedence
570 clearTimeout(this.termTimer);
573 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
576 "command": "termlist",
577 "session": this.sessionID,
578 "name": this.termKeys,
579 "windowid" : window.name,
580 "version" : this.version
584 if ( data.getElementsByTagName("termlist") ) {
586 Number( data.getElementsByTagName("activeclients")[0]
587 .childNodes[0].nodeValue );
588 context.activeClients = activeClients;
589 var termList = { "activeclients": activeClients };
590 var termLists = data.getElementsByTagName("list");
592 for (i = 0; i < termLists.length; i++) {
593 var listName = termLists[i].getAttribute('name');
594 termList[listName] = new Array();
595 var terms = termLists[i].getElementsByTagName('term');
596 //for each term in the list
597 for (j = 0; j < terms.length; j++) {
600 (terms[j].getElementsByTagName("name")[0]
602 ? terms[j].getElementsByTagName("name")[0]
603 .childNodes[0].nodeValue
607 .getElementsByTagName("frequency")[0]
608 .childNodes[0].nodeValue || 'ERROR'
611 // Only for xtargets: id, records, filtered
613 terms[j].getElementsByTagName("id");
614 if(terms[j].getElementsByTagName("id").length)
616 termIdNode[0].childNodes[0].nodeValue;
617 termList[listName][j] = term;
619 var recordsNode = terms[j].getElementsByTagName("records");
620 if (recordsNode && recordsNode.length)
621 term["records"] = recordsNode[0].childNodes[0].nodeValue;
623 var filteredNode = terms[j].getElementsByTagName("filtered");
624 if (filteredNode && filteredNode.length)
625 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
630 context.termCounter++;
631 var delay = context.termTime
632 + context.termCounter * context.dumpFactor;
633 if ( activeClients > 0 )
642 context.termlistCallback(termList);
645 context.throwError('Termlist failed. Malformed WS resonse.',
653 if( !this.initStatusOK && this.useSessions )
655 'Pz2.js: bytarget command has to be preceded with a search command.'
658 // no need to continue
659 if( !this.searchStatusOK )
662 // if called explicitly takes precedence
663 clearTimeout(this.bytargetTimer);
666 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
669 "command": "bytarget",
670 "session": this.sessionID,
672 "windowid" : window.name,
673 "version" : this.version
676 if ( data.getElementsByTagName("status")[0]
677 .childNodes[0].nodeValue == "OK" ) {
678 var targetNodes = data.getElementsByTagName("target");
679 var bytarget = new Array();
680 for ( i = 0; i < targetNodes.length; i++) {
681 bytarget[i] = new Array();
682 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
683 if ( targetNodes[i].childNodes[j].nodeType
684 == Node.ELEMENT_NODE ) {
686 targetNodes[i].childNodes[j].nodeName;
687 if (targetNodes[i].childNodes[j].firstChild != null)
689 var nodeText = targetNodes[i].childNodes[j]
690 .firstChild.nodeValue;
691 bytarget[i][nodeName] = nodeText;
694 bytarget[i][nodeName] = "";
700 if (bytarget[i]["state"]=="Client_Disconnected") {
701 bytarget[i]["hits"] = "Error";
702 } else if (bytarget[i]["state"]=="Client_Error") {
703 bytarget[i]["hits"] = "Error";
704 } else if (bytarget[i]["state"]=="Client_Working") {
705 bytarget[i]["hits"] = "...";
707 if (bytarget[i].diagnostic == "1") {
708 bytarget[i].diagnostic = "Permanent system error";
709 } else if (bytarget[i].diagnostic == "2") {
710 bytarget[i].diagnostic = "Temporary system error";
712 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
713 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
714 var suggestions = targetsSuggestions[0];
715 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
719 context.bytargetCounter++;
720 var delay = context.bytargetTime
721 + context.bytargetCounter * context.dumpFactor;
722 if ( context.activeClients > 0 )
723 context.bytargetTimer =
731 context.bytargetCallback(bytarget);
734 context.throwError('Bytarget failed. Malformed WS resonse.',
740 // just for testing, probably shouldn't be here
741 showNext: function(page)
743 var step = page || 1;
744 this.show( ( step * this.currentNum ) + this.currentStart );
747 showPrev: function(page)
749 if (this.currentStart == 0 )
751 var step = page || 1;
752 var newStart = this.currentStart - (step * this.currentNum );
753 this.show( newStart > 0 ? newStart : 0 );
756 showPage: function(pageNum)
758 //var page = pageNum || 1;
759 this.show(pageNum * this.currentNum);
764 ********************************************************************************
765 ** AJAX HELPER CLASS ***********************************************************
766 ********************************************************************************
768 var pzHttpRequest = function ( url, errorHandler ) {
769 this.maxUrlLength = 2048;
772 this.errorHandler = errorHandler || null;
774 this.requestHeaders = {};
776 if ( window.XMLHttpRequest ) {
777 this.request = new XMLHttpRequest();
778 } else if ( window.ActiveXObject ) {
780 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
782 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
788 pzHttpRequest.prototype =
790 safeGet: function ( params, callback )
792 var encodedParams = this.encodeParams(params);
793 var url = this._urlAppendParams(encodedParams);
794 if (url.length >= this.maxUrlLength) {
795 this.requestHeaders["Content-Type"]
796 = "application/x-www-form-urlencoded";
797 this._send( 'POST', this.url, encodedParams, callback );
799 this._send( 'GET', url, '', callback );
803 get: function ( params, callback )
805 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
809 post: function ( params, data, callback )
811 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
818 this.request.open( 'GET', this.url, this.async );
819 this.request.send('');
820 if ( this.request.status == 200 )
821 return this.request.responseXML;
824 encodeParams: function (params)
828 for (var key in params) {
829 if (params[key] != null) {
830 encoded += sep + key + '=' + encodeURIComponent(params[key]);
837 _send: function ( type, url, data, callback)
840 this.callback = callback;
842 this.request.open( type, url, this.async );
843 for (var key in this.requestHeaders)
844 this.request.setRequestHeader(key, this.requestHeaders[key]);
845 this.request.onreadystatechange = function () {
846 context._handleResponse(url); /// url used ONLY for error reporting
848 this.request.send(data);
851 _urlAppendParams: function (encodedParams)
854 return this.url + "?" + encodedParams;
859 _handleResponse: function (savedUrlForErrorReporting)
861 if ( this.request.readyState == 4 ) {
862 // pick up appplication errors first
864 if (this.request.responseXML &&
865 (errNode = this.request.responseXML.documentElement)
866 && errNode.nodeName == 'error') {
867 var errMsg = errNode.getAttribute("msg");
868 var errCode = errNode.getAttribute("code");
870 if (errNode.childNodes.length)
871 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
873 var err = new Error(errMsg + errAddInfo);
876 if (this.errorHandler) {
877 this.errorHandler(err);
882 } else if (this.request.status == 200 &&
883 this.request.responseXML == null) {
884 if (this.request.responseText != null) {
888 var text = this.request.responseText;
889 if (typeof window.JSON == "undefined")
890 json = eval("(" + text + ")");
893 json = JSON.parse(text);
896 // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
897 /* DEBUG only works in mk2-mobile
898 if (document.getElementById("log"))
899 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
902 json = eval("(" + text + ")");
905 /* DEBUG only works in mk2-mobile
906 if (document.getElementById("log"))
907 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
912 this.callback(json, "json");
914 var err = new Error("XML response is empty but no error " +
915 "for " + savedUrlForErrorReporting);
917 if (this.errorHandler) {
918 this.errorHandler(err);
923 } else if (this.request.status == 200) {
924 this.callback(this.request.responseXML);
926 var err = new Error("HTTP response not OK: "
927 + this.request.status + " - "
928 + this.request.statusText );
929 err.code = '00' + this.request.status;
930 if (this.errorHandler) {
931 this.errorHandler(err);
942 ********************************************************************************
943 ** XML HELPER FUNCTIONS ********************************************************
944 ********************************************************************************
949 if ( window.ActiveXObject) {
950 var DOMDoc = document;
952 var DOMDoc = Document.prototype;
955 DOMDoc.newXmlDoc = function ( root )
959 if (document.implementation && document.implementation.createDocument) {
960 doc = document.implementation.createDocument('', root, null);
961 } else if ( window.ActiveXObject ) {
962 doc = new ActiveXObject("MSXML2.DOMDocument");
963 doc.loadXML('<' + root + '/>');
965 throw new Error ('No XML support in this browser');
972 DOMDoc.parseXmlFromString = function ( xmlString )
976 if ( window.DOMParser ) {
977 var parser = new DOMParser();
978 doc = parser.parseFromString( xmlString, "text/xml");
979 } else if ( window.ActiveXObject ) {
980 doc = new ActiveXObject("MSXML2.DOMDocument");
981 doc.loadXML( xmlString );
983 throw new Error ("No XML parsing support in this browser.");
989 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
991 if ( window.XSLTProcessor ) {
992 var proc = new XSLTProcessor();
993 proc.importStylesheet( xslDoc );
994 return proc.transformToDocument(xmlDoc);
995 } else if ( window.ActiveXObject ) {
996 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
998 alert( 'Unable to perform XSLT transformation in this browser' );
1004 Element_removeFromDoc = function (DOM_Element)
1006 DOM_Element.parentNode.removeChild(DOM_Element);
1009 Element_emptyChildren = function (DOM_Element)
1011 while( DOM_Element.firstChild ) {
1012 DOM_Element.removeChild( DOM_Element.firstChild )
1016 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1018 if ( window.XSLTProcessor ) {
1019 var proc = new XSLTProcessor();
1020 proc.importStylesheet( xslDoc );
1021 var docFrag = false;
1022 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1023 DOM_Element.appendChild(docFrag);
1024 } else if ( window.ActiveXObject ) {
1025 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1027 alert( 'Unable to perform XSLT transformation in this browser' );
1031 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1033 var node = DOM_Element.ownerDocument.createElement(tagName);
1034 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1036 DOM_Element.appendChild(node);
1037 node.appendChild(text);
1042 Element_setTextContent = function ( DOM_Element, textContent )
1044 if (typeof DOM_Element.textContent !== "undefined") {
1045 DOM_Element.textContent = textContent;
1046 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1047 DOM_Element.innerText = textContent;
1049 throw new Error("Cannot set text content of the node, no such method.");
1053 Element_getTextContent = function (DOM_Element)
1055 if ( typeof DOM_Element.textContent != 'undefined' ) {
1056 return DOM_Element.textContent;
1057 } else if (typeof DOM_Element.text != 'undefined') {
1058 return DOM_Element.text;
1060 throw new Error("Cannot get text content of the node, no such method.");
1064 Element_parseChildNodes = function (node)
1067 var hasChildElems = false;
1068 var textContent = '';
1070 if (node.hasChildNodes()) {
1071 var children = node.childNodes;
1072 for (var i = 0; i < children.length; i++) {
1073 var child = children[i];
1074 switch (child.nodeType) {
1075 case Node.ELEMENT_NODE:
1076 hasChildElems = true;
1077 var nodeName = child.nodeName;
1078 if (!(nodeName in parsed))
1079 parsed[nodeName] = [];
1080 parsed[nodeName].push(Element_parseChildNodes(child));
1082 case Node.TEXT_NODE:
1083 textContent += child.nodeValue;
1085 case Node.CDATA_SECTION_NODE:
1086 textContent += child.nodeValue;
1092 var attrs = node.attributes;
1093 for (var i = 0; i < attrs.length; i++) {
1094 hasChildElems = true;
1095 var attrName = '@' + attrs[i].nodeName;
1096 var attrValue = attrs[i].nodeValue;
1097 parsed[attrName] = attrValue;
1100 // if no nested elements/attrs set value to text
1102 parsed['#text'] = textContent;
1104 parsed = textContent;
1109 /* do not remove trailing bracket */