forked from stsvilik/Xml-to-JSON
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxml.min.js
1 lines (1 loc) · 2.7 KB
/
xml.min.js
1
!function(window,undef){function parseXMLString(strXML){var xmlDoc=NULL,out=NULL,isParsed=TRUE;try{xmlDoc="DOMParser"in window?new DOMParser:new ActiveXObject("MSXML2.DOMDocument"),xmlDoc.async=FALSE}catch(e){throw new Error("XML Parser could not be instantiated")}if("parseFromString"in xmlDoc?(out=xmlDoc.parseFromString(strXML,"text/xml"),isParsed="parsererror"!==out.documentElement.tagName):(isParsed=xmlDoc.loadXML(strXML),out=isParsed?xmlDoc:FALSE),!isParsed)throw new Error("Error parsing XML string");return out}function onlyText(obj){return obj&&obj.Text&&1==size(obj)}function keys(collection){var i,c=0;if(collection)for(i in collection)c++;return c}function size(collection){var length=collection?collection.length:0;return"number"==typeof length?length:keys(collection)}"".trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,"")});var XMLConverter,module,NULL=null,FALSE=!1,TRUE=!0,NODE_TYPES={Element:1,Attribute:2,Text:3,CDATA:4,Root:9,Fragment:11};XMLConverter={isUnsafe:FALSE,isXML:function(o){return"object"==typeof o&&o.nodeType!==undef},getRoot:function(doc){return doc.nodeType===NODE_TYPES.Root?doc.documentElement:doc.nodeType===NODE_TYPES.Fragment?doc.firstChild:doc},convert:function(xml){var root,out={},xdoc="string"==typeof xml?parseXMLString(xml):this.isXML(xml)?xml:undef;if(!xdoc)throw new Error("Unable to parse XML");if(xdoc.nodeType===NODE_TYPES.Text||xdoc.nodeType===NODE_TYPES.CDATA)return xdoc.nodeValue;root=this.getRoot(xdoc);var nodename=this.getNodeName(root);return out[nodename]={},this.process(root,out[nodename]),out},getNodeName:function(node){return node.prefix?node.nodeName.replace(node.prefix+":",""):node.nodeName},process:function(node,buff){var child,attr,name,att_name,value,i,j,tmp,iMax,data;if(node.hasChildNodes())for(iMax=node.childNodes.length,i=0;iMax>i;i++)switch(child=node.childNodes[i],child.nodeType){case NODE_TYPES.Text:buff.Text=buff.Text?buff.Text+child.nodeValue.trim():child.nodeValue.trim();break;case NODE_TYPES.CDATA:value=child[child.text?"text":"nodeValue"],buff.Text=buff.Text?buff.Text+value:value;break;case NODE_TYPES.Element:name=this.getNodeName(child),tmp={},this.process(child,tmp),tmp&&size(tmp)>0&&(data=tmp,onlyText(tmp)?data=tmp.Text:tmp.Text&&0===tmp.Text.length&&null==tmp.Text,name in buff?buff[name].length&&buff[name].push?buff[name].push(data):buff[name]=[buff[name],data]:buff[name]=data)}if(node.attributes.length)for(j=node.attributes.length-1;j>=0;j--)attr=node.attributes[j],att_name=attr.name.trim(),value=attr.value,buff[(this.isUnsafe?"":"@")+att_name]=value}},module={xmlToJSON:function(xml,unsafe){return XMLConverter.isUnsafe=unsafe!==undef?unsafe:FALSE,XMLConverter.convert(xml)}},window.xml=window.xml||module}(window);