xml2json.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. ### jQuery XML to JSON Plugin v1.3 - 2013-02-18 ###
  3. * http://www.fyneworks.com/ - diego@fyneworks.com
  4. * Licensed under http://en.wikipedia.org/wiki/MIT_License
  5. ###
  6. Website: http://www.fyneworks.com/jquery/xml-to-json/
  7. */
  8. /*
  9. # INSPIRED BY: http://www.terracoder.com/
  10. AND: http://www.thomasfrank.se/xml_to_json.html
  11. AND: http://www.kawa.net/works/js/xml/objtree-e.html
  12. */
  13. /*
  14. This simple script converts XML (document of code) into a JSON object. It is the combination of 2
  15. 'xml to json' great parsers (see below) which allows for both 'simple' and 'extended' parsing modes.
  16. */
  17. // Avoid collisions
  18. ; if (window.jQuery) (function ($) {
  19. // Add function to jQuery namespace
  20. $.extend({
  21. // converts xml documents and xml text to json object
  22. xml2json: function (xml, extended) {
  23. if (!xml) return {}; // quick fail
  24. //### PARSER LIBRARY
  25. // Core function
  26. function parseXML(node, simple) {
  27. if (!node) return null;
  28. var txt = '', obj = null, att = null;
  29. var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
  30. var nv = node.text || node.nodeValue || '';
  31. /*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
  32. if (node.childNodes) {
  33. if (node.childNodes.length > 0) {
  34. /*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
  35. $.each(node.childNodes, function (n, cn) {
  36. var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
  37. var cnv = cn.text || cn.nodeValue || '';
  38. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
  39. if (cnt == 8) {
  40. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
  41. return; // ignore comment node
  42. }
  43. else if (cnt == 3 || cnt == 4 || !cnn) {
  44. // ignore white-space in between tags
  45. if (cnv.match(/^\s+$/)) {
  46. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
  47. return;
  48. };
  49. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
  50. txt += cnv.replace(/^\s+/, '').replace(/\s+$/, '');
  51. // make sure we ditch trailing spaces from markup
  52. }
  53. else {
  54. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
  55. obj = obj || {};
  56. if (obj[cnn]) {
  57. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
  58. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  59. if (!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
  60. obj[cnn] = myArr(obj[cnn]);
  61. obj[cnn][obj[cnn].length] = parseXML(cn, true/* simple */);
  62. obj[cnn].length = obj[cnn].length;
  63. }
  64. else {
  65. /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
  66. obj[cnn] = parseXML(cn);
  67. };
  68. };
  69. });
  70. }; //node.childNodes.length>0
  71. }; //node.childNodes
  72. if (node.attributes) {
  73. if (node.attributes.length > 0) {
  74. /*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
  75. att = {}; obj = obj || {};
  76. $.each(node.attributes, function (a, at) {
  77. var atn = jsVar('@' + at.name), atv = at.value;
  78. att[atn] = atv;
  79. if (obj[atn]) {
  80. /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
  81. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  82. //if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
  83. obj[cnn] = myArr(obj[cnn]);
  84. obj[atn][obj[atn].length] = atv;
  85. obj[atn].length = obj[atn].length;
  86. }
  87. else {
  88. /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
  89. obj[atn] = atv;
  90. };
  91. });
  92. //obj['attributes'] = att;
  93. }; //node.attributes.length>0
  94. }; //node.attributes
  95. if (obj) {
  96. obj = $.extend((txt != '' ? new String(txt) : {}), /* {text:txt},*/obj || {}/*, att || {}*/);
  97. //txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
  98. txt = (obj.text) ? ([obj.text || '']).concat([txt]) : txt;
  99. if (txt) obj.text = txt;
  100. txt = '';
  101. };
  102. var out = obj || txt;
  103. //console.log([extended, simple, out]);
  104. if (extended) {
  105. if (txt) out = {}; //new String(out);
  106. txt = out.text || txt || '';
  107. if (txt) out.text = txt;
  108. if (!simple) out = myArr(out);
  109. };
  110. return out;
  111. }; // parseXML
  112. // Core Function End
  113. // Utility functions
  114. var jsVar = function (s) { return String(s || '').replace(/-/g, "_"); };
  115. // NEW isNum function: 01/09/2010
  116. // Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
  117. function isNum(s) {
  118. // based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
  119. // few bugs corrected from original function :
  120. // - syntax error : regexp.test(string) instead of string.test(reg)
  121. // - regexp modified to accept comma as decimal mark (latin syntax : 25,24 )
  122. // - regexp modified to reject if no number before decimal mark : ".7" is not accepted
  123. // - string is "trimmed", allowing to accept space at the beginning and end of string
  124. var regexp = /^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
  125. return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
  126. };
  127. // OLD isNum function: (for reference only)
  128. //var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
  129. var myArr = function (o) {
  130. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  131. //if(!o.length) o = [ o ]; o.length=o.length;
  132. if (!$.isArray(o)) o = [o]; o.length = o.length;
  133. // here is where you can attach additional functionality, such as searching and sorting...
  134. return o;
  135. };
  136. // Utility functions End
  137. //### PARSER LIBRARY END
  138. // Convert plain text to xml
  139. if (typeof xml == 'string') xml = $.text2xml(xml);
  140. // Quick fail if not xml (or if this is a node)
  141. if (!xml.nodeType) return;
  142. if (xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
  143. // Find xml root node
  144. var root = (xml.nodeType == 9) ? xml.documentElement : xml;
  145. // Convert xml to json
  146. var out = parseXML(root, true /* simple */);
  147. // Clean-up memory
  148. xml = null; root = null;
  149. // Send output
  150. return out;
  151. },
  152. // Convert text to XML DOM
  153. text2xml: function (str) {
  154. // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
  155. //return $(xml)[0];
  156. /* prior to jquery 1.9 */
  157. /*
  158. var out;
  159. try{
  160. var xml = ((!$.support.opacity && !$.support.style))?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
  161. xml.async = false;
  162. }catch(e){ throw new Error("XML Parser could not be instantiated") };
  163. try{
  164. if((!$.support.opacity && !$.support.style)) out = (xml.loadXML(str))?xml:false;
  165. else out = xml.parseFromString(str, "text/xml");
  166. }catch(e){ throw new Error("Error parsing XML string") };
  167. return out;
  168. */
  169. /* jquery 1.9+ */
  170. return $.parseXML(str);
  171. }
  172. }); // extend $
  173. })(jQuery);