diff --git a/xml2json.js b/xml2json.js index 481e6d7..fdaace4 100644 --- a/xml2json.js +++ b/xml2json.js @@ -64,6 +64,7 @@ if(config.keepCData === undefined) { config.keepCData = false; } + config.parseNumbers = config.parseNumbers || false; } var DOMNodeTypes = { @@ -275,7 +276,6 @@ if(config.arrayAccessForm=="property") delete result["#cdata-section_asArray"]; } - if( result.__cnt == 0 && config.emptyNodeForm=="text" ) { result = ''; } @@ -293,6 +293,13 @@ delete result.__text; } } + else + if (result.__cnt > 1 && result.__text!=null && /^[-+]?[0-9]*\.?[0-9]+$/.test(result.__text) && config.parseNumbers) { + result.__text = parseFloat(result.__text); + } + + delete result["#text"]; + delete result.__cnt; if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) { diff --git a/xml2json.min.js b/xml2json.min.js index e8f9d0a..9158274 100644 --- a/xml2json.min.js +++ b/xml2json.min.js @@ -1 +1 @@ -(function(a,b){if(typeof define==="function"&&define.amd){define([],b);}else{if(typeof exports==="object"){module.exports=b();}else{a.X2JS=b();}}}(this,function(){return function(z){var t="1.2.0";z=z||{};i();u();function i(){if(z.escapeMode===undefined){z.escapeMode=true;}z.attributePrefix=z.attributePrefix||"_";z.arrayAccessForm=z.arrayAccessForm||"none";z.emptyNodeForm=z.emptyNodeForm||"text";if(z.enableToStringFunc===undefined){z.enableToStringFunc=true;}z.arrayAccessFormPaths=z.arrayAccessFormPaths||[];if(z.skipEmptyTextNodesForObj===undefined){z.skipEmptyTextNodesForObj=true;}if(z.stripWhitespaces===undefined){z.stripWhitespaces=true;}z.datetimeAccessFormPaths=z.datetimeAccessFormPaths||[];if(z.useDoubleQuotes===undefined){z.useDoubleQuotes=false;}z.xmlElementsFilter=z.xmlElementsFilter||[];z.jsonPropertiesFilter=z.jsonPropertiesFilter||[];if(z.keepCData===undefined){z.keepCData=false;}}var h={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,COMMENT_NODE:8,DOCUMENT_NODE:9};function u(){}function x(B){var C=B.localName;if(C==null){C=B.baseName;}if(C==null||C==""){C=B.nodeName;}return C;}function r(B){return B.prefix;}function s(B){if(typeof(B)=="string"){return B.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'");}else{return B;}}function k(B){return B.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&");}function w(C,F,D,E){var B=0;for(;B0){if(w(z.arrayAccessFormPaths,D,B,C)){D[B]=[D[B]];}}}function a(G){var E=G.split(/[-T:+Z]/g);var F=new Date(E[0],E[1]-1,E[2]);var D=E[5].split(".");F.setHours(E[3],E[4],D[0]);if(D.length>1){F.setMilliseconds(D[1]);}if(E[6]&&E[7]){var C=E[6]*60+Number(E[7]);var B=/\d\d-\d\d:\d\d$/.test(G)?"-":"+";C=0+(B=="-"?-1*C:C);F.setMinutes(F.getMinutes()-C-F.getTimezoneOffset());}else{if(G.indexOf("Z",G.length-1)!==-1){F=new Date(Date.UTC(F.getFullYear(),F.getMonth(),F.getDate(),F.getHours(),F.getMinutes(),F.getSeconds(),F.getMilliseconds()));}}return F;}function q(D,B,C){if(z.datetimeAccessFormPaths.length>0){var E=C.split(".#")[0];if(w(z.datetimeAccessFormPaths,D,B,E)){return a(D);}else{return D;}}else{return D;}}function b(E,C,B,D){if(C==h.ELEMENT_NODE&&z.xmlElementsFilter.length>0){return w(z.xmlElementsFilter,E,B,D);}else{return true;}}function A(D,J){if(D.nodeType==h.DOCUMENT_NODE){var K=new Object;var B=D.childNodes;for(var L=0;L1&&K.__text!=null&&z.skipEmptyTextNodesForObj){if((z.stripWhitespaces&&K.__text=="")||(K.__text.trim()=="")){delete K.__text;}}}}}delete K.__cnt;if(z.enableToStringFunc&&(K.__text!=null||K.__cdata!=null)){K.toString=function(){return(this.__text!=null?this.__text:"")+(this.__cdata!=null?this.__cdata:"");};}return K;}else{if(D.nodeType==h.TEXT_NODE||D.nodeType==h.CDATA_SECTION_NODE){return D.nodeValue;}}}}function o(I,F,H,C){var E="<"+((I!=null&&I.__prefix!=null)?(I.__prefix+":"):"")+F;if(H!=null){for(var G=0;G";}function v(C,B){return C.indexOf(B,C.length-B.length)!==-1;}function y(C,B){if((z.arrayAccessForm=="property"&&v(B.toString(),("_asArray")))||B.toString().indexOf(z.attributePrefix)==0||B.toString().indexOf("__")==0||(C[B] instanceof Function)){return true;}else{return false;}}function m(D){var C=0;if(D instanceof Object){for(var B in D){if(y(D,B)){continue;}C++;}}return C;}function l(D,B,C){return z.jsonPropertiesFilter.length==0||C==""||w(z.jsonPropertiesFilter,D,B,C);}function c(D){var C=[];if(D instanceof Object){for(var B in D){if(B.toString().indexOf("__")==-1&&B.toString().indexOf(z.attributePrefix)==0){C.push(B);}}}return C;}function g(C){var B="";if(C.__cdata!=null){B+="";}if(C.__text!=null){if(z.escapeMode){B+=s(C.__text);}else{B+=C.__text;}}return B;}function d(C){var B="";if(C instanceof Object){B+=g(C);}else{if(C!=null){if(z.escapeMode){B+=s(C);}else{B+=C;}}}return B;}function p(C,B){if(C===""){return B;}else{return C+"."+B;}}function f(D,G,F,E){var B="";if(D.length==0){B+=o(D,G,F,true);}else{for(var C=0;C0){for(var E in I){if(y(I,E)||(H!=""&&!l(I,E,p(H,E)))){continue;}var D=I[E];var G=c(D);if(D==null||D==undefined){B+=o(D,E,G,true);}else{if(D instanceof Object){if(D instanceof Array){B+=f(D,E,G,H);}else{if(D instanceof Date){B+=o(D,E,G,false);B+=D.toISOString();B+=j(D,E);}else{var C=m(D);if(C>0||D.__text!=null||D.__cdata!=null){B+=o(D,E,G,false);B+=e(D,p(H,E));B+=j(D,E);}else{B+=o(D,E,G,true);}}}}else{B+=o(D,E,G,false);B+=d(D);B+=j(D,E);}}}}B+=d(I);return B;}this.parseXmlString=function(D){var F=window.ActiveXObject||"ActiveXObject" in window;if(D===undefined){return null;}var E;if(window.DOMParser){var G=new window.DOMParser();var B=null;if(!F){try{B=G.parseFromString("INVALID","text/xml").getElementsByTagName("parsererror")[0].namespaceURI;}catch(C){B=null;}}try{E=G.parseFromString(D,"text/xml");if(B!=null&&E.getElementsByTagNameNS(B,"parsererror").length>0){E=null;}}catch(C){E=null;}}else{if(D.indexOf("")+2);}E=new ActiveXObject("Microsoft.XMLDOM");E.async="false";E.loadXML(D);}return E;};this.asArray=function(B){if(B===undefined||B==null){return[];}else{if(B instanceof Array){return B;}else{return[B];}}};this.toXmlDateTime=function(B){if(B instanceof Date){return B.toISOString();}else{if(typeof(B)==="number"){return new Date(B).toISOString();}else{return null;}}};this.asDateTime=function(B){if(typeof(B)=="string"){return a(B);}else{return B;}};this.xml2json=function(B){return A(B);};this.xml_str2json=function(B){var C=this.parseXmlString(B);if(C!=null){return this.xml2json(C);}else{return null;}};this.json2xml_str=function(B){return e(B,"");};this.json2xml=function(C){var B=this.json2xml_str(C);return this.parseXmlString(B);};this.getVersion=function(){return t;};};})); \ No newline at end of file +!function(root,factory){"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?module.exports=factory():root.X2JS=factory()}(this,function(){return function(config){"use strict";function initConfigDefaults(){void 0===config.escapeMode&&(config.escapeMode=!0),config.attributePrefix=config.attributePrefix||"_",config.arrayAccessForm=config.arrayAccessForm||"none",config.emptyNodeForm=config.emptyNodeForm||"text",void 0===config.enableToStringFunc&&(config.enableToStringFunc=!0),config.arrayAccessFormPaths=config.arrayAccessFormPaths||[],void 0===config.skipEmptyTextNodesForObj&&(config.skipEmptyTextNodesForObj=!0),void 0===config.stripWhitespaces&&(config.stripWhitespaces=!0),config.datetimeAccessFormPaths=config.datetimeAccessFormPaths||[],void 0===config.useDoubleQuotes&&(config.useDoubleQuotes=!1),config.xmlElementsFilter=config.xmlElementsFilter||[],config.jsonPropertiesFilter=config.jsonPropertiesFilter||[],void 0===config.keepCData&&(config.keepCData=!1),config.parseNumbers=config.parseNumbers||!1}function initRequiredPolyfills(){}function getNodeLocalName(node){var nodeLocalName=node.localName;return null==nodeLocalName&&(nodeLocalName=node.baseName),null!=nodeLocalName&&""!=nodeLocalName||(nodeLocalName=node.nodeName),nodeLocalName}function getNodePrefix(node){return node.prefix}function escapeXmlChars(str){return"string"==typeof str?str.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):str}function checkInStdFiltersArrayForm(stdFiltersArrayForm,obj,name,path){for(var idx=0;idx0&&checkInStdFiltersArrayForm(config.arrayAccessFormPaths,obj,childName,path)&&(obj[childName]=[obj[childName]])}function fromXmlDateTime(prop){var bits=prop.split(/[-T:+Z]/g),d=new Date(bits[0],bits[1]-1,bits[2]),secondBits=bits[5].split(".");if(d.setHours(bits[3],bits[4],secondBits[0]),secondBits.length>1&&d.setMilliseconds(secondBits[1]),bits[6]&&bits[7]){var offsetMinutes=60*bits[6]+Number(bits[7]),sign=/\d\d-\d\d:\d\d$/.test(prop)?"-":"+";offsetMinutes=0+("-"==sign?-1*offsetMinutes:offsetMinutes),d.setMinutes(d.getMinutes()-offsetMinutes-d.getTimezoneOffset())}else prop.indexOf("Z",prop.length-1)!==-1&&(d=new Date(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds(),d.getMilliseconds())));return d}function checkFromXmlDateTimePaths(value,childName,fullPath){if(config.datetimeAccessFormPaths.length>0){var path=fullPath.split(".#")[0];return checkInStdFiltersArrayForm(config.datetimeAccessFormPaths,value,childName,path)?fromXmlDateTime(value):value}return value}function checkXmlElementsFilter(obj,childType,childName,childPath){return!(childType==DOMNodeTypes.ELEMENT_NODE&&config.xmlElementsFilter.length>0)||checkInStdFiltersArrayForm(config.xmlElementsFilter,obj,childName,childPath)}function parseDOMChildren(node,path){if(node.nodeType==DOMNodeTypes.DOCUMENT_NODE){for(var result=new Object,nodeChildren=node.childNodes,cidx=0;cidx1&&null!=result.__text&&config.skipEmptyTextNodesForObj?(config.stripWhitespaces&&""==result.__text||""==result.__text.trim())&&delete result.__text:result.__cnt>1&&null!=result.__text&&/^[-+]?[0-9]*\.?[0-9]+$/.test(result.__text)&&config.parseNumbers&&(result.__text=parseFloat(result.__text)):result=result.__cdata,delete result["#text"],delete result.__cnt,!config.enableToStringFunc||null==result.__text&&null==result.__cdata||(result.toString=function(){return(null!=this.__text?this.__text:"")+(null!=this.__cdata?this.__cdata:"")}),result}if(node.nodeType==DOMNodeTypes.TEXT_NODE||node.nodeType==DOMNodeTypes.CDATA_SECTION_NODE)return node.nodeValue}function startTag(jsonObj,element,attrList,closed){var resultStr="<"+(null!=jsonObj&&null!=jsonObj.__prefix?jsonObj.__prefix+":":"")+element;if(null!=attrList)for(var aidx=0;aidx":">"}function endTag(jsonObj,elementName){return""}function endsWith(str,suffix){return str.indexOf(suffix,str.length-suffix.length)!==-1}function jsonXmlSpecialElem(jsonObj,jsonObjField){return!!("property"==config.arrayAccessForm&&endsWith(jsonObjField.toString(),"_asArray")||0==jsonObjField.toString().indexOf(config.attributePrefix)||0==jsonObjField.toString().indexOf("__")||jsonObj[jsonObjField]instanceof Function)}function jsonXmlElemCount(jsonObj){var elementsCnt=0;if(jsonObj instanceof Object)for(var it in jsonObj)jsonXmlSpecialElem(jsonObj,it)||elementsCnt++;return elementsCnt}function checkJsonObjPropertiesFilter(jsonObj,propertyName,jsonObjPath){return 0==config.jsonPropertiesFilter.length||""==jsonObjPath||checkInStdFiltersArrayForm(config.jsonPropertiesFilter,jsonObj,propertyName,jsonObjPath)}function parseJSONAttributes(jsonObj){var attrList=[];if(jsonObj instanceof Object)for(var ait in jsonObj)ait.toString().indexOf("__")==-1&&0==ait.toString().indexOf(config.attributePrefix)&&attrList.push(ait);return attrList}function parseJSONTextAttrs(jsonTxtObj){var result="";return null!=jsonTxtObj.__cdata&&(result+=""),null!=jsonTxtObj.__text&&(result+=config.escapeMode?escapeXmlChars(jsonTxtObj.__text):jsonTxtObj.__text),result}function parseJSONTextObject(jsonTxtObj){var result="";return jsonTxtObj instanceof Object?result+=parseJSONTextAttrs(jsonTxtObj):null!=jsonTxtObj&&(result+=config.escapeMode?escapeXmlChars(jsonTxtObj):jsonTxtObj),result}function getJsonPropertyPath(jsonObjPath,jsonPropName){return""===jsonObjPath?jsonPropName:jsonObjPath+"."+jsonPropName}function parseJSONArray(jsonArrRoot,jsonArrObj,attrList,jsonObjPath){var result="";if(0==jsonArrRoot.length)result+=startTag(jsonArrRoot,jsonArrObj,attrList,!0);else for(var arIdx=0;arIdx0)for(var it in jsonObj)if(!jsonXmlSpecialElem(jsonObj,it)&&(""==jsonObjPath||checkJsonObjPropertiesFilter(jsonObj,it,getJsonPropertyPath(jsonObjPath,it)))){var subObj=jsonObj[it],attrList=parseJSONAttributes(subObj);if(null==subObj||void 0==subObj)result+=startTag(subObj,it,attrList,!0);else if(subObj instanceof Object)if(subObj instanceof Array)result+=parseJSONArray(subObj,it,attrList,jsonObjPath);else if(subObj instanceof Date)result+=startTag(subObj,it,attrList,!1),result+=subObj.toISOString(),result+=endTag(subObj,it);else{var subObjElementsCnt=jsonXmlElemCount(subObj);subObjElementsCnt>0||null!=subObj.__text||null!=subObj.__cdata?(result+=startTag(subObj,it,attrList,!1),result+=parseJSONObject(subObj,getJsonPropertyPath(jsonObjPath,it)),result+=endTag(subObj,it)):result+=startTag(subObj,it,attrList,!0)}else result+=startTag(subObj,it,attrList,!1),result+=parseJSONTextObject(subObj),result+=endTag(subObj,it)}return result+=parseJSONTextObject(jsonObj)}var VERSION="1.2.0";config=config||{},initConfigDefaults(),initRequiredPolyfills();var DOMNodeTypes={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,COMMENT_NODE:8,DOCUMENT_NODE:9};this.parseXmlString=function(xmlDocStr){var isIEParser=window.ActiveXObject||"ActiveXObject"in window;if(void 0===xmlDocStr)return null;var xmlDoc;if(window.DOMParser){var parser=new window.DOMParser,parsererrorNS=null;if(!isIEParser)try{parsererrorNS=parser.parseFromString("INVALID","text/xml").getElementsByTagName("parsererror")[0].namespaceURI}catch(err){parsererrorNS=null}try{xmlDoc=parser.parseFromString(xmlDocStr,"text/xml"),null!=parsererrorNS&&xmlDoc.getElementsByTagNameNS(parsererrorNS,"parsererror").length>0&&(xmlDoc=null)}catch(err){xmlDoc=null}}else 0==xmlDocStr.indexOf("")+2)),xmlDoc=new ActiveXObject("Microsoft.XMLDOM"),xmlDoc.async="false",xmlDoc.loadXML(xmlDocStr);return xmlDoc},this.asArray=function(prop){return void 0===prop||null==prop?[]:prop instanceof Array?prop:[prop]},this.toXmlDateTime=function(dt){return dt instanceof Date?dt.toISOString():"number"==typeof dt?new Date(dt).toISOString():null},this.asDateTime=function(prop){return"string"==typeof prop?fromXmlDateTime(prop):prop},this.xml2json=function(xmlDoc){return parseDOMChildren(xmlDoc)},this.xml_str2json=function(xmlDocStr){var xmlDoc=this.parseXmlString(xmlDocStr);return null!=xmlDoc?this.xml2json(xmlDoc):null},this.json2xml_str=function(jsonObj){return parseJSONObject(jsonObj,"")},this.json2xml=function(jsonObj){var xmlDocStr=this.json2xml_str(jsonObj);return this.parseXmlString(xmlDocStr)},this.getVersion=function(){return VERSION}}});