xml2json.js 16 KB

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