jquery.xml2json.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. ### jQuery XML to JSON Plugin v1.1 - 2008-07-01 ###
  3. * http://www.fyneworks.com/ - diego@fyneworks.com
  4. * Dual licensed under the MIT and GPL licenses:
  5. * http://www.opensource.org/licenses/mit-license.php
  6. * http://www.gnu.org/licenses/gpl.html
  7. ###
  8. Website: http://www.fyneworks.com/jquery/xml-to-json/
  9. *//*
  10. # INSPIRED BY: http://www.terracoder.com/
  11. AND: http://www.thomasfrank.se/xml_to_json.html
  12. AND: http://www.kawa.net/works/js/xml/objtree-e.html
  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. if(txt) obj.text = txt;
  99. txt = '';
  100. };
  101. var out = obj || txt;
  102. //console.log([extended, simple, out]);
  103. if(extended){
  104. if(txt) out = {};//new String(out);
  105. txt = out.text || txt || '';
  106. if(txt) out.text = txt;
  107. if(!simple) out = myArr(out);
  108. };
  109. return out;
  110. };// parseXML
  111. // Core Function End
  112. // Utility functions
  113. var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
  114. // NEW isNum function: 01/09/2010
  115. // Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
  116. function isNum(s){
  117. // based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
  118. // few bugs corrected from original function :
  119. // - syntax error : regexp.test(string) instead of string.test(reg)
  120. // - regexp modified to accept comma as decimal mark (latin syntax : 25,24 )
  121. // - regexp modified to reject if no number before decimal mark : ".7" is not accepted
  122. // - string is "trimmed", allowing to accept space at the beginning and end of string
  123. var regexp=/^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
  124. return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
  125. };
  126. // OLD isNum function: (for reference only)
  127. //var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
  128. var myArr = function(o){
  129. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  130. //if(!o.length) o = [ o ]; o.length=o.length;
  131. if(!$.isArray(o)) o = [ o ]; o.length=o.length;
  132. // here is where you can attach additional functionality, such as searching and sorting...
  133. return o;
  134. };
  135. // Utility functions End
  136. //### PARSER LIBRARY END
  137. // Convert plain text to xml
  138. if(typeof xml=='string') xml = $.text2xml(xml);
  139. // Quick fail if not xml (or if this is a node)
  140. if(!xml.nodeType) return;
  141. if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
  142. // Find xml root node
  143. var root = (xml.nodeType == 9) ? xml.documentElement : xml;
  144. // Convert xml to json
  145. var out = parseXML(root, true /* simple */);
  146. // Clean-up memory
  147. xml = null; root = null;
  148. // Send output
  149. return out;
  150. },
  151. // Convert text to XML DOM
  152. text2xml: function(str) {
  153. // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
  154. //return $(xml)[0];
  155. var out;
  156. try{
  157. var xml = ($.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
  158. xml.async = false;
  159. }catch(e){ throw new Error("XML Parser could not be instantiated") };
  160. try{
  161. if($.browser.msie) out = (xml.loadXML(str))?xml:false;
  162. else out = xml.parseFromString(str, "text/xml");
  163. }catch(e){ throw new Error("Error parsing XML string") };
  164. return out;
  165. }
  166. }); // extend $
  167. })(jQuery);