This code solves these two problems:
1. It is known that the js object has no concept of class name, so you must manually specify the top-level node name during conversion.
2. There are also elements in the array. If the object type is an object type, you need to configure the node name of the element of this array.
var XmlHelper=function(){ var _arrayTypes={} var _self=this; /* *Convert object to xml *@obj Target object *@rootname Node Name *@arraytypes Configure the node name of the sub-element of the array field */ =function(obj,rootname,arraytypes){ if(arraytypes){ _arrayTypes=arraytypes; } var xml=""; if(typeof obj!=="undefined"){ if((obj)){ xml+=parseArrayToXML(obj,rootname); }else if(typeof obj==="object"){ xml+=parseObjectToXML(obj,rootname); }else{ xml+=parseGeneralTypeToXML(obj,rootname); } } return xml; } var parseObjectToXML=function(obj,rootname){ if(typeof rootname==="undefined"||!isNaN(Number(rootname))){ rootname="Object"; } var xml="<"+rootname+">"; if(obj){ for(var field in obj){ var value=obj[field]; if(typeof value!=="undefined"){ if((value)){ xml+=parseArrayToXML(value,field); }else if(typeof value==="object"){ xml+=_self.parseToXML(value,field); }else{ xml+=parseGeneralTypeToXML(value,field); } } } } xml+="</"+rootname+">"; return xml; } var parseArrayToXML=function(array,rootname){ if(typeof rootname==="undefined"||!isNaN(Number(rootname))){ rootname="Array"; } var xml="<"+rootname+">"; if(array){ var itemrootname=_arrayTypes[rootname]; (function(item){ xml+=_self.parseToXML(item,itemrootname); }); } xml+="</"+rootname+">"; return xml; } var parseGeneralTypeToXML=function(value,rootname){ if(typeof rootname==="undefined"||!isNaN(Number(rootname))){ rootname=typeof value; } var xml="<"+rootname+">"+value+"</"+rootname+">"; return xml; } } //=============================================================================================================================var xmlhelper=new XmlHelper(); //Example 1var testobj={ field1:"1", field2:true, field3:[{a:1},{a:2}] } ((testobj,"testobj",{field3:"ArrayItem"})); //Output: <testobj><field1>1</field1><field2>true</field2><field3><ArrayItem><a>1</a></ArrayItem><a>2</a></ArrayItem></field3></testobj>("================================================"); //Example 2var testobj2=[1,2,3]; ((testobj2,"testobj2")); //Output:<testobj2><number>1</number><number>2</number><number>3</number></testobj2>
This conversion code has limitations
The field names with the value of the object are better not the same
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!