Advertisement
Guest User

x2js

a guest
Jun 22nd, 2015
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  Copyright 2011-2013 Abdulla Abdurakhmanov
  3.  Original sources are available at https://code.google.com/p/x2js/
  4.  
  5.  Licensed under the Apache License, Version 2.0 (the "License");
  6.  you may not use this file except in compliance with the License.
  7.  You may obtain a copy of the License at
  8.  
  9.  http://www.apache.org/licenses/LICENSE-2.0
  10.  
  11.  Unless required by applicable law or agreed to in writing, software
  12.  distributed under the License is distributed on an "AS IS" BASIS,
  13.  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  See the License for the specific language governing permissions and
  15.  limitations under the License.
  16.  */
  17.  
  18. function X2JS(config) {
  19.     'use strict';
  20.        
  21.     var VERSION = "1.1.3";
  22.    
  23.     config = config || {};
  24.     initConfigDefaults();
  25.    
  26.     function initConfigDefaults() {
  27.         if(config.escapeMode === undefined) {
  28.             config.escapeMode = true;
  29.         }
  30.         config.attributePrefix = config.attributePrefix || "_";
  31.         config.arrayAccessForm = config.arrayAccessForm || "none";
  32.         config.emptyNodeForm = config.emptyNodeForm || "text";
  33.         if(config.enableToStringFunc === undefined) {
  34.             config.enableToStringFunc = true;
  35.         }
  36.         config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
  37.         if(config.skipEmptyTextNodesForObj === undefined) {
  38.             config.skipEmptyTextNodesForObj = true;
  39.         }
  40.     }
  41.  
  42.     var DOMNodeTypes = {
  43.         ELEMENT_NODE       : 1,
  44.         TEXT_NODE          : 3,
  45.         CDATA_SECTION_NODE : 4,
  46.         COMMENT_NODE       : 8,
  47.         DOCUMENT_NODE      : 9
  48.     };
  49.    
  50.     function getNodeLocalName( node ) {
  51.         var nodeLocalName = node.localName;        
  52.         if(nodeLocalName == null) // Yeah, this is IE!!
  53.             nodeLocalName = node.baseName;
  54.         if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too
  55.             nodeLocalName = node.nodeName;
  56.         return nodeLocalName;
  57.     }
  58.    
  59.     function getNodePrefix(node) {
  60.         return node.prefix;
  61.     }
  62.        
  63.     function escapeXmlChars(str) {
  64.         if(typeof(str) == "string")
  65.             return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g, '&#x2F;');
  66.         else
  67.             return str;
  68.     }
  69.  
  70.     function unescapeXmlChars(str) {
  71.         return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#x27;/g, "'").replace(/&#x2F;/g, '\/');
  72.     }
  73.    
  74.     function toArrayAccessForm(obj, childName, path) {
  75.         switch(config.arrayAccessForm) {
  76.         case "property":
  77.             if(!(obj[childName] instanceof Array))
  78.                 obj[childName+"_asArray"] = [obj[childName]];
  79.             else
  80.                 obj[childName+"_asArray"] = obj[childName];
  81.             break;     
  82.         /*case "none":
  83.             break;*/
  84.         }
  85.        
  86.         if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
  87.             var idx = 0;
  88.             for(; idx < config.arrayAccessFormPaths.length; idx++) {
  89.                 var arrayPath = config.arrayAccessFormPaths[idx];
  90.                 if( typeof arrayPath === "string" ) {
  91.                     if(arrayPath == path)
  92.                         break;
  93.                 }
  94.                 else
  95.                 if( arrayPath instanceof RegExp) {
  96.                     if(arrayPath.test(path))
  97.                         break;
  98.                 }              
  99.                 else
  100.                 if( typeof arrayPath === "function") {
  101.                     if(arrayPath(obj, childName, path))
  102.                         break;
  103.                 }
  104.             }
  105.             if(idx!=config.arrayAccessFormPaths.length) {
  106.                 obj[childName] = [obj[childName]];
  107.             }
  108.         }
  109.     }
  110.  
  111.     function parseDOMChildren( node, path ) {
  112.         if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
  113.             var result = new Object;
  114.             var nodeChildren = node.childNodes;
  115.             // Alternative for firstElementChild which is not supported in some environments
  116.             for(var cidx=0; cidx <nodeChildren.length; cidx++) {
  117.                 var child = nodeChildren.item(cidx);
  118.                 if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  119.                     var childName = getNodeLocalName(child);
  120.                     result[childName] = parseDOMChildren(child, childName);
  121.                 }
  122.             }
  123.             return result;
  124.         }
  125.         else
  126.         if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  127.             var result = new Object;
  128.             result.__cnt=0;
  129.            
  130.             var nodeChildren = node.childNodes;
  131.            
  132.             // Children nodes
  133.             for(var cidx=0; cidx <nodeChildren.length; cidx++) {
  134.                 var child = nodeChildren.item(cidx); // nodeChildren[cidx];
  135.                 var childName = getNodeLocalName(child);
  136.                
  137.                 if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {
  138.                     result.__cnt++;
  139.                     if(result[childName] == null) {
  140.                         result[childName] = parseDOMChildren(child, path+"."+childName);
  141.                         toArrayAccessForm(result, childName, path+"."+childName);                  
  142.                     }
  143.                     else {
  144.                         if(result[childName] != null) {
  145.                             if( !(result[childName] instanceof Array)) {
  146.                                 result[childName] = [result[childName]];
  147.                                 toArrayAccessForm(result, childName, path+"."+childName);
  148.                             }
  149.                         }
  150.                         (result[childName])[result[childName].length] = parseDOMChildren(child, path+"."+childName);
  151.                     }
  152.                 }                              
  153.             }
  154.            
  155.             // Attributes
  156.             for(var aidx=0; aidx <node.attributes.length; aidx++) {
  157.                 var attr = node.attributes.item(aidx); // [aidx];
  158.                 result.__cnt++;
  159.                 result[config.attributePrefix+attr.name]=attr.value;
  160.             }
  161.            
  162.             // Node namespace prefix
  163.             var nodePrefix = getNodePrefix(node);
  164.             if(nodePrefix!=null && nodePrefix!="") {
  165.                 result.__cnt++;
  166.                 result.__prefix=nodePrefix;
  167.             }
  168.            
  169.             if(result["#text"]!=null) {            
  170.                 result.__text = result["#text"];
  171.                 if(result.__text instanceof Array) {
  172.                     result.__text = result.__text.join("\n");
  173.                 }
  174.                 if(config.escapeMode)
  175.                     result.__text = unescapeXmlChars(result.__text);
  176.                 delete result["#text"];
  177.                 if(config.arrayAccessForm=="property")
  178.                     delete result["#text_asArray"];
  179.             }
  180.             if(result["#cdata-section"]!=null) {
  181.                 result.__cdata = result["#cdata-section"];
  182.                 delete result["#cdata-section"];
  183.                 if(config.arrayAccessForm=="property")
  184.                     delete result["#cdata-section_asArray"];
  185.             }
  186.            
  187.             if( result.__cnt == 1 && result.__text!=null  ) {
  188.                 result = result.__text;
  189.             }
  190.             else
  191.             if( result.__cnt == 0 && config.emptyNodeForm=="text" ) {
  192.                 result = '';
  193.             }
  194.             else
  195.             if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {
  196.                 if(result.__text.trim()=="") {
  197.                     delete result.__text;
  198.                 }
  199.             }
  200.             delete result.__cnt;           
  201.            
  202.             if( config.enableToStringFunc && result.__text!=null || result.__cdata!=null ) {
  203.                 result.toString = function() {
  204.                     return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');
  205.                 };
  206.             }
  207.             return result;
  208.         }
  209.         else
  210.         if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
  211.             return node.nodeValue;
  212.         }  
  213.     }
  214.    
  215.     function startTag(jsonObj, element, attrList, closed) {
  216.         var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
  217.         if(attrList!=null) {
  218.             for(var aidx = 0; aidx < attrList.length; aidx++) {
  219.                 var attrName = attrList[aidx];
  220.                 var attrVal = jsonObj[attrName];
  221.                 resultStr+=" "+attrName.substr(config.attributePrefix.length)+"='"+attrVal+"'";
  222.             }
  223.         }
  224.         if(!closed)
  225.             resultStr+=">";
  226.         else
  227.             resultStr+="/>";
  228.         return resultStr;
  229.     }
  230.    
  231.     function endTag(jsonObj,elementName) {
  232.         return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
  233.     }
  234.    
  235.     function endsWith(str, suffix) {
  236.         return str.indexOf(suffix, str.length - suffix.length) !== -1;
  237.     }
  238.    
  239.     function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {
  240.         if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray")))
  241.                 || jsonObjField.toString().indexOf(config.attributePrefix)==0
  242.                 || jsonObjField.toString().indexOf("__")==0
  243.                 || (jsonObj[jsonObjField] instanceof Function) )
  244.             return true;
  245.         else
  246.             return false;
  247.     }
  248.    
  249.     function jsonXmlElemCount ( jsonObj ) {
  250.         var elementsCnt = 0;
  251.         if(jsonObj instanceof Object ) {
  252.             for( var it in jsonObj  ) {
  253.                 if(jsonXmlSpecialElem ( jsonObj, it) )
  254.                     continue;          
  255.                 elementsCnt++;
  256.             }
  257.         }
  258.         return elementsCnt;
  259.     }
  260.    
  261.     function parseJSONAttributes ( jsonObj ) {
  262.         var attrList = [];
  263.         if(jsonObj instanceof Object ) {
  264.             for( var ait in jsonObj  ) {
  265.                 if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {
  266.                     attrList.push(ait);
  267.                 }
  268.             }
  269.         }
  270.         return attrList;
  271.     }
  272.    
  273.     function parseJSONTextAttrs ( jsonTxtObj ) {
  274.         var result ="";
  275.        
  276.         if(jsonTxtObj.__cdata!=null) {                                     
  277.             result+="<![CDATA["+jsonTxtObj.__cdata+"]]>";                  
  278.         }
  279.        
  280.         if(jsonTxtObj.__text!=null) {          
  281.             if(config.escapeMode)
  282.                 result+=escapeXmlChars(jsonTxtObj.__text);
  283.             else
  284.                 result+=jsonTxtObj.__text;
  285.         }
  286.         return result;
  287.     }
  288.    
  289.     function parseJSONTextObject ( jsonTxtObj ) {
  290.         var result ="";
  291.  
  292.         if( jsonTxtObj instanceof Object ) {
  293.             result+=parseJSONTextAttrs ( jsonTxtObj );
  294.         }
  295.         else
  296.             if(jsonTxtObj!=null) {
  297.                 if(config.escapeMode)
  298.                     result+=escapeXmlChars(jsonTxtObj);
  299.                 else
  300.                     result+=jsonTxtObj;
  301.             }
  302.        
  303.         return result;
  304.     }
  305.    
  306.     function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList ) {
  307.         var result = "";
  308.         if(jsonArrRoot.length == 0) {
  309.             result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);
  310.         }
  311.         else {
  312.             for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
  313.                 result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
  314.                 result+=parseJSONObject(jsonArrRoot[arIdx]);
  315.                 result+=endTag(jsonArrRoot[arIdx],jsonArrObj);                     
  316.             }
  317.         }
  318.         return result;
  319.     }
  320.    
  321.     function parseJSONObject ( jsonObj ) {
  322.         var result = "";   
  323.  
  324.         var elementsCnt = jsonXmlElemCount ( jsonObj );
  325.        
  326.         if(elementsCnt > 0) {
  327.             for( var it in jsonObj ) {
  328.                
  329.                 if(jsonXmlSpecialElem ( jsonObj, it) )
  330.                     continue;          
  331.                
  332.                 var subObj = jsonObj[it];                      
  333.                
  334.                 var attrList = parseJSONAttributes( subObj )
  335.                
  336.                 if(subObj == null || subObj == undefined) {
  337.                     result+=startTag(subObj, it, attrList, true);
  338.                 }
  339.                 else
  340.                 if(subObj instanceof Object) {
  341.                    
  342.                     if(subObj instanceof Array) {                  
  343.                         result+=parseJSONArray( subObj, it, attrList );                
  344.                     }
  345.                     else {
  346.                         var subObjElementsCnt = jsonXmlElemCount ( subObj );
  347.                         if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {
  348.                             result+=startTag(subObj, it, attrList, false);
  349.                             result+=parseJSONObject(subObj);
  350.                             result+=endTag(subObj,it);
  351.                         }
  352.                         else {
  353.                             result+=startTag(subObj, it, attrList, true);
  354.                         }
  355.                     }
  356.                 }
  357.                 else {
  358.                     result+=startTag(subObj, it, attrList, false);
  359.                     result+=parseJSONTextObject(subObj);
  360.                     result+=endTag(subObj,it);
  361.                 }
  362.             }
  363.         }
  364.         result+=parseJSONTextObject(jsonObj);
  365.        
  366.         return result;
  367.     }
  368.    
  369.     this.parseXmlString = function(xmlDocStr) {
  370.         if (xmlDocStr === undefined) {
  371.             return null;
  372.         }
  373.         var xmlDoc;
  374.         if (window.DOMParser) {
  375.             var parser=new window.DOMParser();         
  376.             xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
  377.         }
  378.         else {
  379.             // IE :(
  380.             if(xmlDocStr.indexOf("<?")==0) {
  381.                 xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
  382.             }
  383.             xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  384.             xmlDoc.async="false";
  385.             xmlDoc.loadXML(xmlDocStr);
  386.         }
  387.         return xmlDoc;
  388.     };
  389.    
  390.     this.asArray = function(prop) {
  391.         if(prop instanceof Array)
  392.             return prop;
  393.         else
  394.             return [prop];
  395.     };
  396.  
  397.     this.xml2json = function (xmlDoc) {
  398.         return parseDOMChildren ( xmlDoc );
  399.     };
  400.    
  401.     this.xml_str2json = function (xmlDocStr) {
  402.         var xmlDoc = this.parseXmlString(xmlDocStr);   
  403.         return this.xml2json(xmlDoc);
  404.     };
  405.  
  406.     this.json2xml_str = function (jsonObj) {
  407.         return parseJSONObject ( jsonObj );
  408.     };
  409.  
  410.     this.json2xml = function (jsonObj) {
  411.         var xmlDocStr = this.json2xml_str (jsonObj);
  412.         return this.parseXmlString(xmlDocStr);
  413.     };
  414.    
  415.     this.getVersion = function () {
  416.         return VERSION;
  417.     };
  418.    
  419. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement