XML string to XML object, XML object to JSON object

Source: Internet
Author: User

XML string to XML object:

function loadXml (str) {  ifnull) {   returnnull;  }   var doc = str;   Try {   = createxmldom ();    false ;   Doc.loadxml (str);  } Catch (e) {   = $.parsexml (str);  }   return Doc;}

/***xml object to JSON object *xmlobj:xml object *nodename: Node path (' Root/item ') *isarray:true, Force return Array Object **/functionXmltojson (xmlobj,nodename,isarray) {varobj=$ (xmlobj); varitemobj={}; varNodenames= ""; vargetallattrs=function(node) {//recursive parsing of XML into JSON objects      var_itemobj={}; varNotnull=false; varnodechilds=Node.childnodes; varchildlenght=nodechilds.length; var_attrs=node.attributes; varFirstnodename= "#text"; Try{firstnodename=nodechilds[0].nodename; }Catch(e) {}if((childlenght>0&&firstnodename!= "#text") | | _attrs.length>0){         var_childs=Nodechilds; var_childslength=nodechilds.length; var_filename_= ""; if(undefined!=_attrs) {           var_attrslength=_attrs.length;  for(vari=0; i<_attrslength; i++) {//Parsing XML node Properties            varAttrname=_attrs[i].nodename; varAttrvalue=_attrs[i].nodevalue; _itemobj[attrname]=Attrvalue; }         }        for(varj = 0; J < _childslength; J + +) {//parsing XML child nodes          var_node =_childs[j]; var_fildname =_node.nodename; if("#text" ==_fildname) { Break;}; if(_itemobj[_fildname]!=undefined) {//If there are duplicate nodes that need to be in array format            if(! (_itemobj[_fildname]instanceofArray)) {              varA=_itemobj[_fildname]; _itemobj[_fildname]=[a];//If the node appears larger than one, the first value is stored in the array            }          }          var_fildvalue=getallattrs (_node); Try{_itemobj[_fildname].push (_fildvalue); }Catch(e) {_itemobj[_fildname]=_fildvalue; _itemobj["Length"]=1; }         }      }Else{_itemobj= (node.textcontent==undefined)?node.text:node.textContent; }      return_itemobj;   }; if(nodename) {nodenames=nodename.split ("/")   }    for(vari=0;i<nodenames.length;i++) {obj=Obj.find (Nodenames[i]); } $ (obj). each (function(key,item) {if(itemobj[item.nodename]!=undefined) {       if(! (Itemobj[item.nodename]instanceofArray)) {         varA=Itemobj[item.nodename]; Itemobj[item.nodename]=[A];     } itemobj[item.nodename].push (Getallattrs (item)); }Else{       if(nodenames.length>0) {Itemobj[item.nodename]=getallattrs (item); }Else{Itemobj[item.firstchild.nodename]=getallattrs (Item.firstchild);   }     }   }); if(nodenames.length>1) {Itemobj=itemobj[nodenames[nodenames.length-1]]; }   if(isarray&&! (ItemobjinstanceofArray) &&itemobj!=undefined) {Itemobj=[Itemobj]; }  returnitemobj;};

How to use:

var xmlstr= "<USERS>" +        "<user state= ' 0 ' >" +        "<username type= ' String ' > Zhang San </ Username> "+        " <userid type= ' String ' >00001</USERID> "+        " </USER> "+        " <user state= ' 1 ' > ' +        ' <username type= ' String ' size= ' + ' > John Doe </USERNAME> ' +        ' <userid>00002</ Userid> "+        " </USER> "+        " <USER> "+        " <USERNAME> John Doe </USERNAME> "+        " < Userid>00002</userid> "+        " </USER> "+        " </USERS> "; var xmlobj=loadxml (XMLSTR);

Xmltojson (xmlobj);//return results are as follows

{  "USERS": {    "USER": [      {        "State": "0",        "USERNAME": {          ' type ': ' String '        },        "Length": 1,        "USERID": {          ' type ': ' String '        }      },      {        "State": "1",        "USERNAME": {          ' type ': ' String ',          "Size": "100"        },        "Length": 1,        "USERID": "00002"      },      {        "USERNAME": "John Doe",        "Length": 1,        "USERID": "00002"      }    ],    "Length": 1  }}

(2) Xmltojson (xmlobj, ' Users/user ', true); The return result is as follows:

[  {   "State": "0",   "USERNAME": {     ' type ': ' String '   },   "Length": 1,   "USERID": {     ' type ': ' String '   }  },  {   "State": "1",   "USERNAME": {     ' type ': ' String ',     "Size": "100"   },   "Length": 1,   "USERID": "00002"  },  {   "USERNAME": "John Doe",   "Length": 1,   "USERID": "00002"  }]

PS: Here are a few more online tools for you to refer to using XML operations:

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

Online format xml/compressed XML online:
Http://tools.jb51.net/code/xmlformat

XML online compression/formatting tool:
Http://tools.jb51.net/code/xml_format_compress

XML code online format beautification tool:
Http://tools.jb51.net/code/xmlcodeformat

XML string to XML object, XML object to JSON object

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.