objtree.js 18 KB

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