objtree.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*##############################################################################
  2. # HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. ############################################################################## */
  16. // ========================================================================
  17. // XML.ObjTree -- XML source code from/to JavaScript object like E4X
  18. // ========================================================================
  19. if ( typeof(XML) == 'undefined' ) XML = function() {};
  20. // constructor
  21. XML.ObjTree = function () {
  22. return this;
  23. };
  24. // class variables
  25. XML.ObjTree.VERSION = "0.24";
  26. // object prototype
  27. XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n';
  28. XML.ObjTree.prototype.attr_prefix = '-';
  29. XML.ObjTree.prototype.overrideMimeType = 'text/xml';
  30. // method: parseXML( xmlsource )
  31. XML.ObjTree.prototype.parseXML = function ( xml ) {
  32. var root;
  33. if ( window.DOMParser ) {
  34. var xmldom = new DOMParser();
  35. // xmldom.async = false; // DOMParser is always sync-mode
  36. var dom = xmldom.parseFromString( xml, "application/xml" );
  37. if ( ! dom ) return;
  38. root = dom.documentElement;
  39. } else if ( window.ActiveXObject ) {
  40. xmldom = new ActiveXObject('Microsoft.XMLDOM');
  41. xmldom.async = false;
  42. xmldom.loadXML( xml );
  43. root = xmldom.documentElement;
  44. }
  45. if ( ! root ) return;
  46. return this.parseDOM( root );
  47. };
  48. // method: parseHTTP( url, options, callback )
  49. XML.ObjTree.prototype.parseHTTP = function ( url, options, callback ) {
  50. var myopt = {};
  51. for( var key in options ) {
  52. myopt[key] = options[key]; // copy object
  53. }
  54. if ( ! myopt.method ) {
  55. if ( typeof(myopt.postBody) == "undefined" &&
  56. typeof(myopt.postbody) == "undefined" &&
  57. typeof(myopt.parameters) == "undefined" ) {
  58. myopt.method = "get";
  59. } else {
  60. myopt.method = "post";
  61. }
  62. }
  63. if ( callback ) {
  64. myopt.asynchronous = true; // async-mode
  65. var __this = this;
  66. var __func = callback;
  67. var __save = myopt.onComplete;
  68. myopt.onComplete = function ( trans ) {
  69. var tree;
  70. if ( trans && trans.responseXML && trans.responseXML.documentElement ) {
  71. tree = __this.parseDOM( trans.responseXML.documentElement );
  72. } else if ( trans && trans.responseText ) {
  73. tree = __this.parseXML( trans.responseText );
  74. }
  75. __func( tree, trans );
  76. if ( __save ) __save( trans );
  77. };
  78. } else {
  79. myopt.asynchronous = false; // sync-mode
  80. }
  81. var trans;
  82. if ( typeof(HTTP) != "undefined" && HTTP.Request ) {
  83. myopt.uri = url;
  84. var req = new HTTP.Request( myopt ); // JSAN
  85. if ( req ) trans = req.transport;
  86. } else if ( typeof(Ajax) != "undefined" && Ajax.Request ) {
  87. var req = new Ajax.Request( url, myopt ); // ptorotype.js
  88. if ( req ) trans = req.transport;
  89. }
  90. // if ( trans && typeof(trans.overrideMimeType) != "undefined" ) {
  91. // trans.overrideMimeType( this.overrideMimeType );
  92. // }
  93. if ( callback ) return trans;
  94. if ( trans && trans.responseXML && trans.responseXML.documentElement ) {
  95. return this.parseDOM( trans.responseXML.documentElement );
  96. } else if ( trans && trans.responseText ) {
  97. return this.parseXML( trans.responseText );
  98. }
  99. }
  100. // method: parseDOM( documentroot )
  101. XML.ObjTree.prototype.parseDOM = function ( root ) {
  102. if ( ! root ) return;
  103. this.__force_array = {};
  104. if ( this.force_array ) {
  105. for( var i=0; i<this.force_array.length; i++ ) {
  106. this.__force_array[this.force_array[i]] = 1;
  107. }
  108. }
  109. var json = this.parseElement( root ); // parse root node
  110. if ( this.__force_array[root.nodeName] ) {
  111. json = [ json ];
  112. }
  113. if ( root.nodeType != 11 ) { // DOCUMENT_FRAGMENT_NODE
  114. var tmp = {};
  115. tmp[root.nodeName] = json; // root nodeName
  116. json = tmp;
  117. }
  118. return json;
  119. };
  120. // method: parseElement( element )
  121. XML.ObjTree.prototype.parseElement = function ( elem ) {
  122. // COMMENT_NODE
  123. if ( elem.nodeType == 7 ) {
  124. return;
  125. }
  126. // TEXT_NODE CDATA_SECTION_NODE
  127. if ( elem.nodeType == 3 || elem.nodeType == 4 ) {
  128. var bool = elem.nodeValue.match( /[^\x00-\x20]/ );
  129. if ( bool == null ) return; // ignore white spaces
  130. return elem.nodeValue;
  131. }
  132. var retval;
  133. var cnt = {};
  134. // parse attributes
  135. if ( elem.attributes && elem.attributes.length ) {
  136. retval = {};
  137. for ( var i=0; i<elem.attributes.length; i++ ) {
  138. var key = elem.attributes[i].nodeName;
  139. if ( typeof(key) != "string" ) continue;
  140. var val = elem.attributes[i].nodeValue;
  141. if ( ! val ) continue;
  142. key = this.attr_prefix + key;
  143. if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
  144. cnt[key] ++;
  145. this.addNode( retval, key, cnt[key], val );
  146. }
  147. }
  148. // parse child nodes (recursive)
  149. if ( elem.childNodes && elem.childNodes.length ) {
  150. var textonly = true;
  151. if ( retval ) textonly = false; // some attributes exists
  152. for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {
  153. var ntype = elem.childNodes[i].nodeType;
  154. if ( ntype == 3 || ntype == 4 ) continue;
  155. textonly = false;
  156. }
  157. if ( textonly ) {
  158. if ( ! retval ) retval = "";
  159. for ( var i=0; i<elem.childNodes.length; i++ ) {
  160. retval += elem.childNodes[i].nodeValue;
  161. }
  162. } else {
  163. if ( ! retval ) retval = {};
  164. for ( var i=0; i<elem.childNodes.length; i++ ) {
  165. var key = elem.childNodes[i].nodeName;
  166. if ( typeof(key) != "string" ) continue;
  167. var val = this.parseElement( elem.childNodes[i] );
  168. if ( ! val ) continue;
  169. if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
  170. cnt[key] ++;
  171. this.addNode( retval, key, cnt[key], val );
  172. }
  173. }
  174. }
  175. return retval;
  176. };
  177. // method: addNode( hash, key, count, value )
  178. XML.ObjTree.prototype.addNode = function ( hash, key, cnts, val ) {
  179. if ( this.__force_array[key] ) {
  180. if ( cnts == 1 ) hash[key] = [];
  181. hash[key][hash[key].length] = val; // push
  182. } else if ( cnts == 1 ) { // 1st sibling
  183. hash[key] = val;
  184. } else if ( cnts == 2 ) { // 2nd sibling
  185. hash[key] = [ hash[key], val ];
  186. } else { // 3rd sibling and more
  187. hash[key][hash[key].length] = val;
  188. }
  189. };
  190. // method: writeXML( tree )
  191. XML.ObjTree.prototype.writeXML = function ( tree ) {
  192. var xml = this.hash_to_xml( null, tree );
  193. return this.xmlDecl + xml;
  194. };
  195. // method: hash_to_xml( tagName, tree )
  196. XML.ObjTree.prototype.hash_to_xml = function ( name, tree ) {
  197. var elem = [];
  198. var attr = [];
  199. for( var key in tree ) {
  200. if ( ! tree.hasOwnProperty(key) ) continue;
  201. var val = tree[key];
  202. if ( key.charAt(0) != this.attr_prefix ) {
  203. if ( typeof(val) == "undefined" || val == null ) {
  204. elem[elem.length] = "<"+key+" />";
  205. } else if ( typeof(val) == "object" && val.constructor == Array ) {
  206. elem[elem.length] = this.array_to_xml( key, val );
  207. } else if ( typeof(val) == "object" ) {
  208. elem[elem.length] = this.hash_to_xml( key, val );
  209. } else {
  210. elem[elem.length] = this.scalar_to_xml( key, val );
  211. }
  212. } else {
  213. attr[attr.length] = " "+(key.substring(1))+'="'+(this.xml_escape( val ))+'"';
  214. }
  215. }
  216. var jattr = attr.join("");
  217. var jelem = elem.join("");
  218. if ( typeof(name) == "undefined" || name == null ) {
  219. // no tag
  220. } else if ( elem.length > 0 ) {
  221. if ( jelem.match( /\n/ )) {
  222. jelem = "<"+name+jattr+">\n"+jelem+"</"+name+">\n";
  223. } else {
  224. jelem = "<"+name+jattr+">" +jelem+"</"+name+">\n";
  225. }
  226. } else {
  227. jelem = "<"+name+jattr+" />\n";
  228. }
  229. return jelem;
  230. };
  231. // method: array_to_xml( tagName, array )
  232. XML.ObjTree.prototype.array_to_xml = function ( name, array ) {
  233. var out = [];
  234. for( var i=0; i<array.length; i++ ) {
  235. var val = array[i];
  236. if ( typeof(val) == "undefined" || val == null ) {
  237. out[out.length] = "<"+name+" />";
  238. } else if ( typeof(val) == "object" && val.constructor == Array ) {
  239. out[out.length] = this.array_to_xml( name, val );
  240. } else if ( typeof(val) == "object" ) {
  241. out[out.length] = this.hash_to_xml( name, val );
  242. } else {
  243. out[out.length] = this.scalar_to_xml( name, val );
  244. }
  245. }
  246. return out.join("");
  247. };
  248. // method: scalar_to_xml( tagName, text )
  249. XML.ObjTree.prototype.scalar_to_xml = function ( name, text ) {
  250. if ( name == "#text" ) {
  251. return this.xml_escape(text);
  252. } else {
  253. return "<"+name+">"+this.xml_escape(text)+"</"+name+">\n";
  254. }
  255. };
  256. // method: xml_escape( text )
  257. XML.ObjTree.prototype.xml_escape = function ( text ) {
  258. return String(text).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  259. };
  260. /*
  261. // ========================================================================
  262. =head1 NAME
  263. XML.ObjTree -- XML source code from/to JavaScript object like E4X
  264. =head1 SYNOPSIS
  265. var xotree = new XML.ObjTree();
  266. var tree1 = {
  267. root: {
  268. node: "Hello, World!"
  269. }
  270. };
  271. var xml1 = xotree.writeXML( tree1 ); // object tree to XML source
  272. alert( "xml1: "+xml1 );
  273. var xml2 = '<?xml version="1.0"?><response><error>0</error></response>';
  274. var tree2 = xotree.parseXML( xml2 ); // XML source to object tree
  275. alert( "error: "+tree2.response.error );
  276. =head1 DESCRIPTION
  277. XML.ObjTree class is a parser/generater between XML source code
  278. and JavaScript object like E4X, ECMAScript for XML.
  279. This is a JavaScript version of the XML::TreePP module for Perl.
  280. This also works as a wrapper for XMLHTTPRequest and successor to JKL.ParseXML class
  281. when this is used with prototype.js or JSAN's HTTP.Request class.
  282. =head2 JavaScript object tree format
  283. A sample XML source:
  284. <?xml version="1.0" encoding="UTF-8"?>
  285. <family name="Kawasaki">
  286. <father>Yasuhisa</father>
  287. <mother>Chizuko</mother>
  288. <children>
  289. <girl>Shiori</girl>
  290. <boy>Yusuke</boy>
  291. <boy>Kairi</boy>
  292. </children>
  293. </family>
  294. Its JavaScript object tree like JSON/E4X:
  295. {
  296. 'family': {
  297. '-name': 'Kawasaki',
  298. 'father': 'Yasuhisa',
  299. 'mother': 'Chizuko',
  300. 'children': {
  301. 'girl': 'Shiori'
  302. 'boy': [
  303. 'Yusuke',
  304. 'Kairi'
  305. ]
  306. }
  307. }
  308. };
  309. Each elements are parsed into objects:
  310. tree.family.father; # the father's given name.
  311. Prefix '-' is inserted before every attributes' name.
  312. tree.family["-name"]; # this family's family name
  313. A array is used because this family has two boys.
  314. tree.family.children.boy[0]; # first boy's name
  315. tree.family.children.boy[1]; # second boy's name
  316. tree.family.children.girl; # (girl has no other sisiters)
  317. =head1 METHODS
  318. =head2 xotree = new XML.ObjTree()
  319. This constructor method returns a new XML.ObjTree object.
  320. =head2 xotree.force_array = [ "rdf:li", "item", "-xmlns" ];
  321. This property allows you to specify a list of element names
  322. which should always be forced into an array representation.
  323. The default value is null, it means that context of the elements
  324. will determine to make array or to keep it scalar.
  325. =head2 xotree.attr_prefix = '@';
  326. This property allows you to specify a prefix character which is
  327. inserted before each attribute names.
  328. Instead of default prefix '-', E4X-style prefix '@' is also available.
  329. The default character is '-'.
  330. Or set '@' to access attribute values like E4X, ECMAScript for XML.
  331. The length of attr_prefix must be just one character and not be empty.
  332. =head2 xotree.xmlDecl = '';
  333. This library generates an XML declaration on writing an XML code per default.
  334. This property forces to change or leave it empty.
  335. =head2 tree = xotree.parseXML( xmlsrc );
  336. This method loads an XML document using the supplied string
  337. and returns its JavaScript object converted.
  338. =head2 tree = xotree.parseDOM( domnode );
  339. This method parses a DOM tree (ex. responseXML.documentElement)
  340. and returns its JavaScript object converted.
  341. =head2 tree = xotree.parseHTTP( url, options );
  342. This method loads a XML file from remote web server
  343. and returns its JavaScript object converted.
  344. XMLHTTPRequest's synchronous mode is always used.
  345. This mode blocks the process until the response is completed.
  346. First argument is a XML file's URL
  347. which must exist in the same domain as parent HTML file's.
  348. Cross-domain loading is not available for security reasons.
  349. Second argument is options' object which can contains some parameters:
  350. method, postBody, parameters, onLoading, etc.
  351. This method requires JSAN's L<HTTP.Request> class or prototype.js's Ajax.Request class.
  352. =head2 xotree.parseHTTP( url, options, callback );
  353. If a callback function is set as third argument,
  354. XMLHTTPRequest's asynchronous mode is used.
  355. This mode calls a callback function with XML file's JavaScript object converted
  356. after the response is completed.
  357. =head2 xmlsrc = xotree.writeXML( tree );
  358. This method parses a JavaScript object tree
  359. and returns its XML source generated.
  360. =head1 EXAMPLES
  361. =head2 Text node and attributes
  362. If a element has both of a text node and attributes
  363. or both of a text node and other child nodes,
  364. text node's value is moved to a special node named "#text".
  365. var xotree = new XML.ObjTree();
  366. var xmlsrc = '<span class="author">Kawasaki Yusuke</span>';
  367. var tree = xotree.parseXML( xmlsrc );
  368. var class = tree.span["-class"]; # attribute
  369. var name = tree.span["#text"]; # text node
  370. =head2 parseHTTP() method with HTTP-GET and sync-mode
  371. HTTP/Request.js or prototype.js must be loaded before calling this method.
  372. var xotree = new XML.ObjTree();
  373. var url = "http://example.com/index.html";
  374. var tree = xotree.parseHTTP( url );
  375. xotree.attr_prefix = '@'; // E4X-style
  376. alert( tree.html["@lang"] );
  377. This code shows C<lang=""> attribute from a X-HTML source code.
  378. =head2 parseHTTP() method with HTTP-POST and async-mode
  379. Third argument is a callback function which is called on onComplete.
  380. var xotree = new XML.ObjTree();
  381. var url = "http://example.com/mt-tb.cgi";
  382. var opts = {
  383. postBody: "title=...&excerpt=...&url=...&blog_name=..."
  384. };
  385. var func = function ( tree ) {
  386. alert( tree.response.error );
  387. };
  388. xotree.parseHTTP( url, opts, func );
  389. This code send a trackback ping and shows its response code.
  390. =head2 Simple RSS reader
  391. This is a RSS reader which loads RDF file and displays all items.
  392. var xotree = new XML.ObjTree();
  393. xotree.force_array = [ "rdf:li", "item" ];
  394. var url = "http://example.com/news-rdf.xml";
  395. var func = function( tree ) {
  396. var elem = document.getElementById("rss_here");
  397. for( var i=0; i<tree["rdf:RDF"].item.length; i++ ) {
  398. var divtag = document.createElement( "div" );
  399. var atag = document.createElement( "a" );
  400. atag.href = tree["rdf:RDF"].item[i].link;
  401. var title = tree["rdf:RDF"].item[i].title;
  402. var tnode = document.createTextNode( title );
  403. atag.appendChild( tnode );
  404. divtag.appendChild( atag );
  405. elem.appendChild( divtag );
  406. }
  407. };
  408. xotree.parseHTTP( url, {}, func );
  409. =head2 XML-RPC using writeXML, prototype.js and parseDOM
  410. If you wish to use prototype.js's Ajax.Request class by yourself:
  411. var xotree = new XML.ObjTree();
  412. var reqtree = {
  413. methodCall: {
  414. methodName: "weblogUpdates.ping",
  415. params: {
  416. param: [
  417. { value: "Kawa.net xp top page" }, // 1st param
  418. { value: "http://www.kawa.net/" } // 2nd param
  419. ]
  420. }
  421. }
  422. };
  423. var reqxml = xotree.writeXML( reqtree ); // JS-Object to XML code
  424. var url = "http://example.com/xmlrpc";
  425. var func = function( req ) {
  426. var resdom = req.responseXML.documentElement;
  427. xotree.force_array = [ "member" ];
  428. var restree = xotree.parseDOM( resdom ); // XML-DOM to JS-Object
  429. alert( restree.methodResponse.params.param.value.struct.member[0].value.string );
  430. };
  431. var opt = {
  432. method: "post",
  433. postBody: reqxml,
  434. asynchronous: true,
  435. onComplete: func
  436. };
  437. new Ajax.Request( url, opt );
  438. =head1 AUTHOR
  439. Yusuke Kawasaki http://www.kawa.net/
  440. =head1 COPYRIGHT AND LICENSE
  441. Copyright (c) 2005-2006 Yusuke Kawasaki. All rights reserved.
  442. This program is free software; you can redistribute it and/or
  443. modify it under the Artistic license. Or whatever license I choose,
  444. which I will do instead of keeping this documentation like it is.
  445. =cut
  446. // ========================================================================
  447. */