Created
May 25, 2015 09:35
-
-
Save HektorW/4663af3b7c5431c9f915 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports=xmlToJSON;var xmlToJSON=function(){this.version="1.3";var e={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},t=new RegExp(/(?!xmlns)^.*:/),r=new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){return this.parseXML(this.stringToXML(e),t)},this.parseXML=function(a,n){for(var s in n)e[s]=n[s];var l={},i=0,o="";if(e.xmlns&&a.namespaceURI&&(l[e.namespaceKey]=a.namespaceURI),a.attributes&&a.attributes.length>0){var u={};for(i;i<a.attributes.length;i++){var c=a.attributes.item(i);m={};var p="";p=e.stripAttrPrefix?c.name.replace(t,""):c.name,m[e.valueKey]=e.grokAttr?this.grokType(c.value.replace(r,"")):c.value.replace(r,""),e.xmlns&&c.namespaceURI&&(m[e.namespaceKey]=c.namespaceURI),e.attrsAsObject?u[p]=m:l[e.attrKey+p]=m}e.attrsAsObject&&(l[e.attrKey]=u)}if(a.hasChildNodes())for(var d,y,m,x=0;x<a.childNodes.length;x++)d=a.childNodes.item(x),4===d.nodeType?e.mergeCDATA?o+=d.nodeValue:l.hasOwnProperty(e.cdataKey)?(l[e.cdataKey].constructor!==Array&&(l[e.cdataKey]=[l[e.cdataKey]]),l[e.cdataKey].push(d.nodeValue)):e.childrenAsArray?(l[e.cdataKey]=[],l[e.cdataKey].push(d.nodeValue)):l[e.cdataKey]=d.nodeValue:3===d.nodeType?o+=d.nodeValue:1===d.nodeType&&(0===i&&(l={}),y=e.stripElemPrefix?d.nodeName.replace(t,""):d.nodeName,m=xmlToJSON.parseXML(d),l.hasOwnProperty(y)?(l[y].constructor!==Array&&(l[y]=[l[y]]),l[y].push(m)):(e.childrenAsArray?(l[y]=[],l[y].push(m)):l[y]=m,i++));else o||(e.childrenAsArray?(l[e.textKey]=[],l[e.textKey].push(null)):l[e.textKey]=null);if(o)if(e.grokText){var h=this.grokType(o.replace(r,""));null!==h&&void 0!==h&&(l[e.textKey]=h)}else l[e.textKey]=e.normalize?o.replace(r,"").replace(/\s+/g," "):o.replace(r,"");return l},this.xmlToString=function(e){try{var t=e.xml?e.xml:(new XMLSerializer).serializeToString(e);return t}catch(r){return null}},this.stringToXML=function(e){try{var t=null;if(window.DOMParser){var r=new DOMParser;return t=r.parseFromString(e,"text/xml")}return t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e),t}catch(a){return null}},this}();"undefined"!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:"function"==typeof define&&define.amd&&define(function(){return xmlToJSON}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment