From 89b98ff74e86f4d26f82df27bf96b3ae86e00ba9 Mon Sep 17 00:00:00 2001 From: anvog Date: Mon, 18 Apr 2016 13:24:47 +0200 Subject: [PATCH 1/4] Update xml2json.js Adds a new feature to keep the order of an XML for user specific items. --- xml2json.js | 1230 +++++++++++++++++++++++++++------------------------ 1 file changed, 663 insertions(+), 567 deletions(-) diff --git a/xml2json.js b/xml2json.js index 481e6d7..d293811 100644 --- a/xml2json.js +++ b/xml2json.js @@ -13,573 +13,669 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + + Fork: + Adds a new feature to keep the order of an XML for user specific items. + Take note: It will add a new container to keep your items in order. + + Original sources are available at https://github.com/anvog/x2js/tree/Feature-keepOrder + + + Example: + + Source: + + + 1 + 2 + 3 + + + a + b + a + + Outcome: json with keepOrder + a + b + a + + {"list":{"a":["1","3"],"b":"2"}} + + Back to XML: + + + 1 + 3 + 2 + + + Outcome: without keepOrder xml to json + a + a + b + + {"list":{"x2jsOrderContainer":[{a:1}, {b:2}, {a:3}]}} + + Back to XML: + + + 1 + 2 + 3 + */ (function (root, factory) { - if (typeof define === "function" && define.amd) { - define([], factory); - } else if (typeof exports === "object") { - module.exports = factory(); - } else { - root.X2JS = factory(); - } - }(this, function () { - return function (config) { - 'use strict'; - - var VERSION = "1.2.0"; - - config = config || {}; - initConfigDefaults(); - initRequiredPolyfills(); - - function initConfigDefaults() { - if(config.escapeMode === undefined) { - config.escapeMode = true; - } - - config.attributePrefix = config.attributePrefix || "_"; - config.arrayAccessForm = config.arrayAccessForm || "none"; - config.emptyNodeForm = config.emptyNodeForm || "text"; - - if(config.enableToStringFunc === undefined) { - config.enableToStringFunc = true; - } - config.arrayAccessFormPaths = config.arrayAccessFormPaths || []; - if(config.skipEmptyTextNodesForObj === undefined) { - config.skipEmptyTextNodesForObj = true; - } - if(config.stripWhitespaces === undefined) { - config.stripWhitespaces = true; - } - config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || []; - - if(config.useDoubleQuotes === undefined) { - config.useDoubleQuotes = false; - } - - config.xmlElementsFilter = config.xmlElementsFilter || []; - config.jsonPropertiesFilter = config.jsonPropertiesFilter || []; - - if(config.keepCData === undefined) { - config.keepCData = false; - } - } - - var DOMNodeTypes = { - ELEMENT_NODE : 1, - TEXT_NODE : 3, - CDATA_SECTION_NODE : 4, - COMMENT_NODE : 8, - DOCUMENT_NODE : 9 - }; - - function initRequiredPolyfills() { - } - - function getNodeLocalName( node ) { - var nodeLocalName = node.localName; - if(nodeLocalName == null) // Yeah, this is IE!! - nodeLocalName = node.baseName; - if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too - nodeLocalName = node.nodeName; - return nodeLocalName; - } - - function getNodePrefix(node) { - return node.prefix; - } - - function escapeXmlChars(str) { - if(typeof(str) == "string") - return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); - else - return str; - } - - function unescapeXmlChars(str) { - return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); - } - - function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) { - var idx = 0; - for(; idx < stdFiltersArrayForm.length; idx++) { - var filterPath = stdFiltersArrayForm[idx]; - if( typeof filterPath === "string" ) { - if(filterPath == path) - break; - } - else - if( filterPath instanceof RegExp) { - if(filterPath.test(path)) - break; - } - else - if( typeof filterPath === "function") { - if(filterPath(obj, name, path)) - break; - } - } - return idx!=stdFiltersArrayForm.length; - } - - function toArrayAccessForm(obj, childName, path) { - switch(config.arrayAccessForm) { - case "property": - if(!(obj[childName] instanceof Array)) - obj[childName+"_asArray"] = [obj[childName]]; - else - obj[childName+"_asArray"] = obj[childName]; - break; - /*case "none": - break;*/ - } - - if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) { - if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) { - obj[childName] = [obj[childName]]; - } - } - } - - function fromXmlDateTime(prop) { - // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object - // Improved to support full spec and optional parts - var bits = prop.split(/[-T:+Z]/g); - - var d = new Date(bits[0], bits[1]-1, bits[2]); - var secondBits = bits[5].split("\."); - d.setHours(bits[3], bits[4], secondBits[0]); - if(secondBits.length>1) - d.setMilliseconds(secondBits[1]); - - // Get supplied time zone offset in minutes - if(bits[6] && bits[7]) { - var offsetMinutes = bits[6] * 60 + Number(bits[7]); - var sign = /\d\d-\d\d:\d\d$/.test(prop)? '-' : '+'; - - // Apply the sign - offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes); - - // Apply offset and local timezone - d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset()) - } - else - if(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())); - } - - // d is now a local time equivalent to the supplied time - return d; - } - - function checkFromXmlDateTimePaths(value, childName, fullPath) { - if(config.datetimeAccessFormPaths.length > 0) { - var path = fullPath.split("\.#")[0]; - if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) { - return fromXmlDateTime(value); - } - else - return value; - } - else - return value; - } - - function checkXmlElementsFilter(obj, childType, childName, childPath) { - if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) { - return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath); - } - else - return true; - } - - function parseDOMChildren( node, path ) { - if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) { - var result = new Object; - var nodeChildren = node.childNodes; - // Alternative for firstElementChild which is not supported in some environments - for(var cidx=0; cidx 1 && result.__text!=null && config.skipEmptyTextNodesForObj) { - if( (config.stripWhitespaces && result.__text=="") || (result.__text.trim()=="")) { - delete result.__text; - } - } - delete result.__cnt; - - if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) { - result.toString = function() { - return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:''); - }; - } - - return result; - } - else - if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) { - return node.nodeValue; - } - } - - function startTag(jsonObj, element, attrList, closed) { - var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element; - if(attrList!=null) { - for(var aidx = 0; aidx < attrList.length; aidx++) { - var attrName = attrList[aidx]; - var attrVal = jsonObj[attrName]; - if(config.escapeMode) - attrVal=escapeXmlChars(attrVal); - resultStr+=" "+attrName.substr(config.attributePrefix.length)+"="; - if(config.useDoubleQuotes) - resultStr+='"'+attrVal+'"'; - else - resultStr+="'"+attrVal+"'"; - } - } - if(!closed) - resultStr+=">"; - else - resultStr+="/>"; - return resultStr; - } - - function endTag(jsonObj,elementName) { - return ""; - } - - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - function jsonXmlSpecialElem ( jsonObj, jsonObjField ) { - if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray"))) - || jsonObjField.toString().indexOf(config.attributePrefix)==0 - || jsonObjField.toString().indexOf("__")==0 - || (jsonObj[jsonObjField] instanceof Function) ) - return true; - else - return false; - } - - function jsonXmlElemCount ( jsonObj ) { - var elementsCnt = 0; - if(jsonObj instanceof Object ) { - for( var it in jsonObj ) { - if(jsonXmlSpecialElem ( jsonObj, it) ) - continue; - elementsCnt++; - } - } - return elementsCnt; - } - - function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) { - return config.jsonPropertiesFilter.length == 0 - || jsonObjPath=="" - || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath); - } - - function parseJSONAttributes ( jsonObj ) { - var attrList = []; - if(jsonObj instanceof Object ) { - for( var ait in jsonObj ) { - if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) { - attrList.push(ait); - } - } - } - return attrList; - } - - function parseJSONTextAttrs ( jsonTxtObj ) { - var result =""; - - if(jsonTxtObj.__cdata!=null) { - result+=""; - } - - if(jsonTxtObj.__text!=null) { - if(config.escapeMode) - result+=escapeXmlChars(jsonTxtObj.__text); - else - result+=jsonTxtObj.__text; - } - return result; - } - - function parseJSONTextObject ( jsonTxtObj ) { - var result =""; - - if( jsonTxtObj instanceof Object ) { - result+=parseJSONTextAttrs ( jsonTxtObj ); - } - else - if(jsonTxtObj!=null) { - if(config.escapeMode) - result+=escapeXmlChars(jsonTxtObj); - else - result+=jsonTxtObj; - } - - return result; - } - - function getJsonPropertyPath(jsonObjPath, jsonPropName) { - if (jsonObjPath==="") { - return jsonPropName; - } - else - return jsonObjPath+"."+jsonPropName; - } - - function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) { - var result = ""; - if(jsonArrRoot.length == 0) { - result+=startTag(jsonArrRoot, jsonArrObj, attrList, true); - } - else { - for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) { - result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false); - result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj)); - result+=endTag(jsonArrRoot[arIdx],jsonArrObj); - } - } - return result; - } - - function parseJSONObject ( jsonObj, jsonObjPath ) { - var result = ""; - - var elementsCnt = jsonXmlElemCount ( jsonObj ); - - if(elementsCnt > 0) { - for( var it in jsonObj ) { - - if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!="" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) ) - continue; - - var subObj = jsonObj[it]; - - var attrList = parseJSONAttributes( subObj ) - - if(subObj == null || subObj == undefined) { - result+=startTag(subObj, it, attrList, true); - } - 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, false); - result+=subObj.toISOString(); - result+=endTag(subObj,it); - } - else { - var subObjElementsCnt = jsonXmlElemCount ( subObj ); - if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) { - result+=startTag(subObj, it, attrList, false); - result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it)); - result+=endTag(subObj,it); - } - else { - result+=startTag(subObj, it, attrList, true); - } - } - } - else { - result+=startTag(subObj, it, attrList, false); - result+=parseJSONTextObject(subObj); - result+=endTag(subObj,it); - } - } - } - result+=parseJSONTextObject(jsonObj); - - return result; - } - - this.parseXmlString = function(xmlDocStr) { - var isIEParser = window.ActiveXObject || "ActiveXObject" in window; - if (xmlDocStr === undefined) { - return null; - } - var xmlDoc; - if (window.DOMParser) { - var parser=new window.DOMParser(); - var parsererrorNS = null; - // IE9+ now is here - if(!isIEParser) { - try { - parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI; - } - catch(err) { - parsererrorNS = null; - } - } - try { - xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" ); - if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) { - //throw new Error('Error parsing XML: '+xmlDocStr); - xmlDoc = null; - } - } - catch(err) { - xmlDoc = null; - } - } - else { - // IE :( - if(xmlDocStr.indexOf("") + 2 ); - } - xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async="false"; - xmlDoc.loadXML(xmlDocStr); - } - return xmlDoc; - }; - - this.asArray = function(prop) { - if (prop === undefined || prop == null) - return []; - else - if(prop instanceof Array) - return prop; - else - return [prop]; - }; - - this.toXmlDateTime = function(dt) { - if(dt instanceof Date) - return dt.toISOString(); - else - if(typeof(dt) === 'number' ) - return new Date(dt).toISOString(); - else - return null; - }; - - this.asDateTime = function(prop) { - if(typeof(prop) == "string") { - return fromXmlDateTime(prop); - } - else - return prop; - }; - - this.xml2json = function (xmlDoc) { - return parseDOMChildren ( xmlDoc ); - }; - - this.xml_str2json = function (xmlDocStr) { - var xmlDoc = this.parseXmlString(xmlDocStr); - if(xmlDoc!=null) - return this.xml2json(xmlDoc); - else - return 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; - }; - } -})) \ No newline at end of file + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof exports === "object") { + module.exports = factory(); + } else { + root.X2JS = factory(); + } +}(this, function () { + return function (config) { + 'use strict'; + + var VERSION = "1.2.0"; + + config = config || {}; + initConfigDefaults(); + initRequiredPolyfills(); + + function initConfigDefaults() { + if (config.escapeMode === undefined) { + config.escapeMode = true; + } + + config.attributePrefix = config.attributePrefix || "_"; + config.arrayAccessForm = config.arrayAccessForm || "none"; + config.emptyNodeForm = config.emptyNodeForm || "text"; + + if (config.enableToStringFunc === undefined) { + config.enableToStringFunc = true; + } + config.arrayAccessFormPaths = config.arrayAccessFormPaths || []; + if (config.skipEmptyTextNodesForObj === undefined) { + config.skipEmptyTextNodesForObj = true; + } + if (config.stripWhitespaces === undefined) { + config.stripWhitespaces = true; + } + config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || []; + + if (config.useDoubleQuotes === undefined) { + config.useDoubleQuotes = false; + } + + config.xmlElementsFilter = config.xmlElementsFilter || []; + config.jsonPropertiesFilter = config.jsonPropertiesFilter || []; + + if (config.keepCData === undefined) { + config.keepCData = false; + } + + // Fork: Add config to enable the new Feature + if (config.keepOrder === undefined) { + config.keepOrder = false; + } + config.orderContainerName = config.orderContainerName || "x2jsOrderContainer"; + config.arrayOrderItems = config.arrayOrderItems || []; + } + + var DOMNodeTypes = { + ELEMENT_NODE: 1, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9 + }; + + function initRequiredPolyfills() { + } + + function getNodeLocalName(node) { + var nodeLocalName = node.localName; + if (nodeLocalName == null) // Yeah, this is IE!! + nodeLocalName = node.baseName; + if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too + nodeLocalName = node.nodeName; + return nodeLocalName; + } + + function getNodePrefix(node) { + return node.prefix; + } + + function escapeXmlChars(str) { + if (typeof (str) == "string") + return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + else + return str; + } + + function unescapeXmlChars(str) { + return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + } + + function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) { + var idx = 0; + for (; idx < stdFiltersArrayForm.length; idx++) { + var filterPath = stdFiltersArrayForm[idx]; + if (typeof filterPath === "string") { + if (filterPath == path) + break; + } + else + if (filterPath instanceof RegExp) { + if (filterPath.test(path)) + break; + } + else + if (typeof filterPath === "function") { + if (filterPath(obj, name, path)) + break; + } + } + return idx != stdFiltersArrayForm.length; + } + + function toArrayAccessForm(obj, childName, path) { + switch (config.arrayAccessForm) { + case "property": + if (!(obj[childName] instanceof Array)) + obj[childName + "_asArray"] = [obj[childName]]; + else + obj[childName + "_asArray"] = obj[childName]; + break; + /*case "none": + break;*/ + } + + if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) { + if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) { + obj[childName] = [obj[childName]]; + } + } + } + + function fromXmlDateTime(prop) { + // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object + // Improved to support full spec and optional parts + var bits = prop.split(/[-T:+Z]/g); + + var d = new Date(bits[0], bits[1] - 1, bits[2]); + var secondBits = bits[5].split("\."); + d.setHours(bits[3], bits[4], secondBits[0]); + if (secondBits.length > 1) + d.setMilliseconds(secondBits[1]); + + // Get supplied time zone offset in minutes + if (bits[6] && bits[7]) { + var offsetMinutes = bits[6] * 60 + Number(bits[7]); + var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+'; + + // Apply the sign + offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes); + + // Apply offset and local timezone + d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset()) + } + else + if (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())); + } + + // d is now a local time equivalent to the supplied time + return d; + } + + function checkFromXmlDateTimePaths(value, childName, fullPath) { + if (config.datetimeAccessFormPaths.length > 0) { + var path = fullPath.split("\.#")[0]; + if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) { + return fromXmlDateTime(value); + } + else + return value; + } + else + return value; + } + + function checkXmlElementsFilter(obj, childType, childName, childPath) { + if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) { + return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath); + } + else + return true; + } + + function parseDOMChildren(node, path) { + if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) { + var result = new Object; + var nodeChildren = node.childNodes; + // Alternative for firstElementChild which is not supported in some environments + for (var cidx = 0; cidx < nodeChildren.length; cidx++) { + var child = nodeChildren.item(cidx); + if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) { + var childName = getNodeLocalName(child); + result[childName] = parseDOMChildren(child, childName); + } + } + return result; + } + else + if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) { + var result = new Object; + result.__cnt = 0; + + var nodeChildren = node.childNodes; + + // Children nodes + for (var cidx = 0; cidx < nodeChildren.length; cidx++) { + var child = nodeChildren.item(cidx); // nodeChildren[cidx]; + var childName = getNodeLocalName(child); + + if (child.nodeType != DOMNodeTypes.COMMENT_NODE) { + var childPath = path + "." + childName; + if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) { + result.__cnt++; + + if (result[childName] == null) { + + // handle orderItems + var containsChild = config.arrayOrderItems.indexOf(childName) >= 0; + if (config.keepOrder && config.arrayOrderItems.length > 0) { + if (containsChild) { + if (!result.hasOwnProperty(config.orderContainerName)) { + result[config.orderContainerName] = new Array(); + } + } + + //if (result instanceof Array && childName != "#text") { + if (config.arrayOrderItems.indexOf(childName) >= 0) { + if (result.hasOwnProperty(config.orderContainerName) && childName != "#text") { + var tmp = {}; + tmp[childName] = parseDOMChildren(child, childPath); + result[config.orderContainerName].push(tmp); + } + } + else { + result[childName] = parseDOMChildren(child, childPath); + } + } else { + result[childName] = parseDOMChildren(child, childPath); + } + + toArrayAccessForm(result, childName, childPath); + } + else { + if (result[childName] != null) { + if (!(result[childName] instanceof Array)) { + result[childName] = [result[childName]]; + toArrayAccessForm(result, childName, childPath); + } + } + (result[childName])[result[childName].length] = parseDOMChildren(child, childPath); + } + } + } + } + + // Attributes + for (var aidx = 0; aidx < node.attributes.length; aidx++) { + var attr = node.attributes.item(aidx); // [aidx]; + result.__cnt++; + result[config.attributePrefix + attr.name] = attr.value; + } + + // Node namespace prefix + var nodePrefix = getNodePrefix(node); + if (nodePrefix != null && nodePrefix != "") { + result.__cnt++; + result.__prefix = nodePrefix; + } + + if (result["#text"] != null) { + result.__text = result["#text"]; + if (result.__text instanceof Array) { + result.__text = result.__text.join("\n"); + } + //if(config.escapeMode) + // result.__text = unescapeXmlChars(result.__text); + if (config.stripWhitespaces) + result.__text = result.__text.trim(); + delete result["#text"]; + if (config.arrayAccessForm == "property") + delete result["#text_asArray"]; + result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName); + } + if (result["#cdata-section"] != null) { + result.__cdata = result["#cdata-section"]; + delete result["#cdata-section"]; + if (config.arrayAccessForm == "property") + delete result["#cdata-section_asArray"]; + } + + if (result.__cnt == 0 && config.emptyNodeForm == "text") { + result = ''; + } + else + if (result.__cnt == 1 && result.__text != null) { + result = result.__text; + } + else + if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) { + result = result.__cdata; + } + else + if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) { + if ((config.stripWhitespaces && result.__text == "") || (result.__text.trim() == "")) { + delete result.__text; + } + } + delete result.__cnt; + + if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) { + result.toString = function () { + return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : ''); + }; + } + + return result; + } + else + if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) { + return node.nodeValue; + } + } + + function startTag(jsonObj, element, attrList, closed) { + var resultStr = "<" + ((jsonObj != null && jsonObj.__prefix != null) ? (jsonObj.__prefix + ":") : "") + element; + if (attrList != null) { + for (var aidx = 0; aidx < attrList.length; aidx++) { + var attrName = attrList[aidx]; + var attrVal = jsonObj[attrName]; + if (config.escapeMode) + attrVal = escapeXmlChars(attrVal); + resultStr += " " + attrName.substr(config.attributePrefix.length) + "="; + if (config.useDoubleQuotes) + resultStr += '"' + attrVal + '"'; + else + resultStr += "'" + attrVal + "'"; + } + } + if (!closed) + resultStr += ">"; + else + resultStr += "/>"; + return resultStr; + } + + function endTag(jsonObj, elementName) { + return ""; + } + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + function jsonXmlSpecialElem(jsonObj, jsonObjField) { + if ((config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), ("_asArray"))) + || jsonObjField.toString().indexOf(config.attributePrefix) == 0 + || jsonObjField.toString().indexOf("__") == 0 + || (jsonObj[jsonObjField] instanceof Function)) + return true; + else + return false; + } + + function jsonXmlElemCount(jsonObj) { + var elementsCnt = 0; + if (jsonObj instanceof Object) { + for (var it in jsonObj) { + if (jsonXmlSpecialElem(jsonObj, it)) + continue; + elementsCnt++; + } + } + return elementsCnt; + } + + function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) { + return config.jsonPropertiesFilter.length == 0 + || jsonObjPath == "" + || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath); + } + + function parseJSONAttributes(jsonObj) { + var attrList = []; + if (jsonObj instanceof Object) { + for (var ait in jsonObj) { + if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) { + attrList.push(ait); + } + } + } + return attrList; + } + + function parseJSONTextAttrs(jsonTxtObj) { + var result = ""; + + if (jsonTxtObj.__cdata != null) { + result += ""; + } + + if (jsonTxtObj.__text != null) { + if (config.escapeMode) + result += escapeXmlChars(jsonTxtObj.__text); + else + result += jsonTxtObj.__text; + } + return result; + } + + function parseJSONTextObject(jsonTxtObj) { + var result = ""; + + if (jsonTxtObj instanceof Object) { + result += parseJSONTextAttrs(jsonTxtObj); + } + else + if (jsonTxtObj != null) { + if (config.escapeMode) + result += escapeXmlChars(jsonTxtObj); + else + result += jsonTxtObj; + } + + return result; + } + + function getJsonPropertyPath(jsonObjPath, jsonPropName) { + if (jsonObjPath === "") { + return jsonPropName; + } + else + return jsonObjPath + "." + jsonPropName; + } + + function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) { + var result = ""; + if (jsonArrRoot.length == 0) { + result += startTag(jsonArrRoot, jsonArrObj, attrList, true); + } + else { + if (config.keepOrder) { + for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) { + if (jsonArrObj != config.orderContainerName) { + result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false); + } + result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj)); + if (jsonArrObj != config.orderContainerName) { + result += endTag(jsonArrRoot[arIdx], jsonArrObj); + } + } + } else { + for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) { + result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false); + result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj)); + result += endTag(jsonArrRoot[arIdx], jsonArrObj); + } + } + + } + return result; + } + + function parseJSONObject(jsonObj, jsonObjPath) { + var result = ""; + + var elementsCnt = jsonXmlElemCount(jsonObj); + + if (elementsCnt > 0) { + for (var it in jsonObj) { + + if (jsonXmlSpecialElem(jsonObj, it) || (jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it)))) + continue; + + var subObj = jsonObj[it]; + + var attrList = parseJSONAttributes(subObj) + + if (subObj == null || subObj == undefined) { + result += startTag(subObj, it, attrList, true); + } + 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, false); + result += subObj.toISOString(); + result += endTag(subObj, it); + } + else { + var subObjElementsCnt = jsonXmlElemCount(subObj); + if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) { + result += startTag(subObj, it, attrList, false); + result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it)); + result += endTag(subObj, it); + } + else { + result += startTag(subObj, it, attrList, true); + } + } + } + else { + result += startTag(subObj, it, attrList, false); + result += parseJSONTextObject(subObj); + result += endTag(subObj, it); + } + } + } + result += parseJSONTextObject(jsonObj); + + return result; + } + + this.parseXmlString = function (xmlDocStr) { + var isIEParser = window.ActiveXObject || "ActiveXObject" in window; + if (xmlDocStr === undefined) { + return null; + } + var xmlDoc; + if (window.DOMParser) { + var parser = new window.DOMParser(); + var parsererrorNS = null; + // IE9+ now is here + if (!isIEParser) { + try { + parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI; + } + catch (err) { + parsererrorNS = null; + } + } + try { + xmlDoc = parser.parseFromString(xmlDocStr, "text/xml"); + if (parsererrorNS != null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) { + //throw new Error('Error parsing XML: '+xmlDocStr); + xmlDoc = null; + } + } + catch (err) { + xmlDoc = null; + } + } + else { + // IE :( + if (xmlDocStr.indexOf("") + 2); + } + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = "false"; + xmlDoc.loadXML(xmlDocStr); + } + return xmlDoc; + }; + + this.asArray = function (prop) { + if (prop === undefined || prop == null) + return []; + else + if (prop instanceof Array) + return prop; + else + return [prop]; + }; + + this.toXmlDateTime = function (dt) { + if (dt instanceof Date) + return dt.toISOString(); + else + if (typeof (dt) === 'number') + return new Date(dt).toISOString(); + else + return null; + }; + + this.asDateTime = function (prop) { + if (typeof (prop) == "string") { + return fromXmlDateTime(prop); + } + else + return prop; + }; + + this.xml2json = function (xmlDoc) { + return parseDOMChildren(xmlDoc); + }; + + this.xml_str2json = function (xmlDocStr) { + var xmlDoc = this.parseXmlString(xmlDocStr); + if (xmlDoc != null) + return this.xml2json(xmlDoc); + else + return 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; + }; + }; +})); From 79d82755a2d9941b3a57765c31b8d05b1eeeabe9 Mon Sep 17 00:00:00 2001 From: anvog Date: Mon, 18 Jul 2016 11:05:55 +0200 Subject: [PATCH 2/4] Update xml2json.js Added options description and fixed example. --- xml2json.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/xml2json.js b/xml2json.js index d293811..1d0debd 100644 --- a/xml2json.js +++ b/xml2json.js @@ -20,9 +20,20 @@ Original sources are available at https://github.com/anvog/x2js/tree/Feature-keepOrder + New options: + keepOrder: boolean, default: false - enables the feature + orderContainerName: string, default: x2jsOrderContainer - name of the json object that contains the elements which should keep the order + arrayOrderItems: array of strings - name of the elements that should keep the order + Example: + var x2js = new X2JS({ + keepOrder: true, + orderContainerName: "x2jsOrderContainer", + arrayOrderItems: ["a", "b"] + }); + Source: @@ -35,10 +46,10 @@ b a - Outcome: json with keepOrder + Outcome: json without keepOrder a - b a + b {"list":{"a":["1","3"],"b":"2"}} @@ -50,10 +61,10 @@ 2 - Outcome: without keepOrder xml to json - a + Outcome: with keepOrder xml to json a b + a {"list":{"x2jsOrderContainer":[{a:1}, {b:2}, {a:3}]}} From 26785a3a0870ad4cf3c1b9da676890227122b573 Mon Sep 17 00:00:00 2001 From: anvog Date: Mon, 18 Jul 2016 11:10:31 +0200 Subject: [PATCH 3/4] Update xml2json.min.js Added min --- xml2json.min.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xml2json.min.js b/xml2json.min.js index e8f9d0a..3841b92 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(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.X2JS=t()}(this,function(){return function(e){"use strict";function t(){void 0===e.escapeMode&&(e.escapeMode=!0),e.attributePrefix=e.attributePrefix||"_",e.arrayAccessForm=e.arrayAccessForm||"none",e.emptyNodeForm=e.emptyNodeForm||"text",void 0===e.enableToStringFunc&&(e.enableToStringFunc=!0),e.arrayAccessFormPaths=e.arrayAccessFormPaths||[],void 0===e.skipEmptyTextNodesForObj&&(e.skipEmptyTextNodesForObj=!0),void 0===e.stripWhitespaces&&(e.stripWhitespaces=!0),e.datetimeAccessFormPaths=e.datetimeAccessFormPaths||[],void 0===e.useDoubleQuotes&&(e.useDoubleQuotes=!1),e.xmlElementsFilter=e.xmlElementsFilter||[],e.jsonPropertiesFilter=e.jsonPropertiesFilter||[],void 0===e.keepCData&&(e.keepCData=!1),void 0===e.keepOrder&&(e.keepOrder=!1),e.orderContainerName=e.orderContainerName||"x2jsOrderContainer",e.arrayOrderItems=e.arrayOrderItems||[]}function r(){}function n(e){var t=e.localName;return null==t&&(t=e.baseName),null!=t&&""!=t||(t=e.nodeName),t}function i(e){return e.prefix}function a(e){return"string"==typeof e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):e}function o(e,t,r,n){for(var i=0;i0&&o(e.arrayAccessFormPaths,t,r,n)&&(t[r]=[t[r]])}function l(e){var t=e.split(/[-T:+Z]/g),r=new Date(t[0],t[1]-1,t[2]),n=t[5].split(".");if(r.setHours(t[3],t[4],n[0]),n.length>1&&r.setMilliseconds(n[1]),t[6]&&t[7]){var i=60*t[6]+Number(t[7]),a=/\d\d-\d\d:\d\d$/.test(e)?"-":"+";i=0+("-"==a?-1*i:i),r.setMinutes(r.getMinutes()-i-r.getTimezoneOffset())}else-1!==e.indexOf("Z",e.length-1)&&(r=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds())));return r}function c(t,r,n){if(e.datetimeAccessFormPaths.length>0){var i=n.split(".#")[0];return o(e.datetimeAccessFormPaths,t,r,i)?l(t):t}return t}function u(t,r,n,i){return r==T.ELEMENT_NODE&&e.xmlElementsFilter.length>0?o(e.xmlElementsFilter,t,n,i):!0}function f(t,r){if(t.nodeType==T.DOCUMENT_NODE){for(var a=new Object,o=t.childNodes,l=0;l=0;if(e.keepOrder&&e.arrayOrderItems.length>0)if(m&&(a.hasOwnProperty(e.orderContainerName)||(a[e.orderContainerName]=new Array)),e.arrayOrderItems.indexOf(d)>=0){if(a.hasOwnProperty(e.orderContainerName)&&"#text"!=d){var x={};x[d]=f(_,p),a[e.orderContainerName].push(x)}}else a[d]=f(_,p);else a[d]=f(_,p);s(a,d,p)}else null!=a[d]&&(a[d]instanceof Array||(a[d]=[a[d]],s(a,d,p))),a[d][a[d].length]=f(_,p)}}for(var g=0;g1&&null!=a.__text&&e.skipEmptyTextNodesForObj&&(e.stripWhitespaces&&""==a.__text||""==a.__text.trim())&&delete a.__text:a=a.__cdata,delete a.__cnt,!e.enableToStringFunc||null==a.__text&&null==a.__cdata||(a.toString=function(){return(null!=this.__text?this.__text:"")+(null!=this.__cdata?this.__cdata:"")}),a}return t.nodeType==T.TEXT_NODE||t.nodeType==T.CDATA_SECTION_NODE?t.nodeValue:void 0}function _(t,r,n,i){var o="<"+(null!=t&&null!=t.__prefix?t.__prefix+":":"")+r;if(null!=n)for(var s=0;s":">"}function d(e,t){return""}function p(e,t){return-1!==e.indexOf(t,e.length-t.length)}function m(t,r){return!!("property"==e.arrayAccessForm&&p(r.toString(),"_asArray")||0==r.toString().indexOf(e.attributePrefix)||0==r.toString().indexOf("__")||t[r]instanceof Function)}function x(e){var t=0;if(e instanceof Object)for(var r in e)m(e,r)||t++;return t}function g(t,r,n){return 0==e.jsonPropertiesFilter.length||""==n||o(e.jsonPropertiesFilter,t,r,n)}function h(t){var r=[];if(t instanceof Object)for(var n in t)-1==n.toString().indexOf("__")&&0==n.toString().indexOf(e.attributePrefix)&&r.push(n);return r}function y(t){var r="";return null!=t.__cdata&&(r+=""),null!=t.__text&&(r+=e.escapeMode?a(t.__text):t.__text),r}function O(t){var r="";return t instanceof Object?r+=y(t):null!=t&&(r+=e.escapeMode?a(t):t),r}function v(e,t){return""===e?t:e+"."+t}function N(t,r,n,i){var a="";if(0==t.length)a+=_(t,r,n,!0);else if(e.keepOrder)for(var o=0;o0)for(var i in e)if(!m(e,i)&&(""==t||g(e,i,v(t,i)))){var a=e[i],o=h(a);if(null==a||void 0==a)r+=_(a,i,o,!0);else if(a instanceof Object)if(a instanceof Array)r+=N(a,i,o,t);else if(a instanceof Date)r+=_(a,i,o,!1),r+=a.toISOString(),r+=d(a,i);else{var s=x(a);s>0||null!=a.__text||null!=a.__cdata?(r+=_(a,i,o,!1),r+=E(a,v(t,i)),r+=d(a,i)):r+=_(a,i,o,!0)}else r+=_(a,i,o,!1),r+=O(a),r+=d(a,i)}return r+=O(e)}var A="1.2.0";e=e||{},t(),r();var T={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,COMMENT_NODE:8,DOCUMENT_NODE:9};this.parseXmlString=function(e){var t=window.ActiveXObject||"ActiveXObject"in window;if(void 0===e)return null;var r;if(window.DOMParser){var n=new window.DOMParser,i=null;if(!t)try{i=n.parseFromString("INVALID","text/xml").getElementsByTagName("parsererror")[0].namespaceURI}catch(a){i=null}try{r=n.parseFromString(e,"text/xml"),null!=i&&r.getElementsByTagNameNS(i,"parsererror").length>0&&(r=null)}catch(a){r=null}}else 0==e.indexOf("")+2)),r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(e);return r},this.asArray=function(e){return void 0===e||null==e?[]:e instanceof Array?e:[e]},this.toXmlDateTime=function(e){return e instanceof Date?e.toISOString():"number"==typeof e?new Date(e).toISOString():null},this.asDateTime=function(e){return"string"==typeof e?l(e):e},this.xml2json=function(e){return f(e)},this.xml_str2json=function(e){var t=this.parseXmlString(e);return null!=t?this.xml2json(t):null},this.json2xml_str=function(e){return E(e,"")},this.json2xml=function(e){var t=this.json2xml_str(e);return this.parseXmlString(t)},this.getVersion=function(){return A}}}); From 71bc5340030784c69700d84b7a9e1bf28564f737 Mon Sep 17 00:00:00 2001 From: anvog Date: Mon, 18 Jul 2016 11:35:41 +0200 Subject: [PATCH 4/4] Update README.md Added fork config options --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 3fe3253..f4946ac 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,18 @@ x2js - XML to JSON and vice versa for JavaScript This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and has no any dependencies. + +## Fork: + Adds a new feature to keep the order of an XML for user specific items. + Take note: It will add a new container to keep your items in order. + + New config options: + * `keepOrder: true|false` Default: false - Enables the feature + * `orderContainerName: ""` Default: x2jsOrderContainer - Name of the json object that contains the elements which should keep the order + * `arrayOrderItems: []` - Array with the names of the elements that should keep the order + +==== + ## API functions * `new X2JS()` - to create your own instance to access all library functionality