JavaScript XML string converted to JSON object

Source: Internet
Author: User
Tags tagname text to json xml parser jquery library

Tag:javascript   xml   json    convert    

/* # # JQuery XML to JSON Plugin v1.2-2013-02-18 # # # * http://www.fyneworks.com/-[email protected]* Licensed Unde R Http://en.wikipedia.org/wiki/MIT_License # # # website:http://www.fyneworks.com/jquery/xml-to-json/*//* # INSPIRED by:http://www.terracoder.com/and:http://www.thomasfrank.se/xml_to_json.htmland:http://www.kawa.net/works/js/ xml/objtree-e.html*//* This simple script converts XML (document of code) into a JSON object. It is the combination of 2 ' XML to JSON ' great parsers (see below) which allows for both ' simple ' and ' extended ' parsing m odes.*///Avoid collisions;if (window.jquery) (function ($) {//Add function to JQuery namespace $.extend ({//converts XML documents and XML text to JSON object Xml2json:function (XML, Extended) {if (!xml) return {};//quick fail//    # # # PARSER LIBRARY//Core function function parsexml (node, simple) {if (!node) return null;    var txt = ', obj = null, ATT = null; var nt = node.nodetype, nn = Jsvar (noDe.localname | |    Node.nodename); var NV = Node.text | | Node.nodevalue | |    '';    /*dbg*///if (Window.console) console.log ([' x2j ', nn,nt,nv.length+ ' bytes ']); if (node.childnodes) {if (node.childnodes.length>0) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' Childre      N ', node.childnodes]);       $.each (Node.childnodes, function (N,CN) {var cnt = Cn.nodetype, cnn = Jsvar (Cn.localname | | cn.nodename); var Cnv = Cn.text | | Cn.nodevalue | |       '';       /*dbg*///if (Window.console) console.log ([' x2j ', nn, ' node>a ', Cnn,cnt,cnv]);        if (cnt = = 8) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' node>b ', CNN, ' COMMENT (Ignore) ']); Return        Ignore comment node} else if (cnt = = 3 | | cnt = = 4 | |!cnn) {//Ignore white-space in between tags if (Cnv.match (/^\s+$/)) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' node>c ', CNN, ' White-space (IGN         ore));        Return        }; /*dbg*///if (Window.console) CONsole.log ([' x2j ', nn, ' node>d ', CNN, ' TEXT ']);        TXT + = Cnv.replace (/^\s+/, "). Replace (/\s+$/,");/Make sure we ditch trailing spaces from markup} else{        /*dbg*///if (Window.console) console.log ([' x2j ', nn, ' node>e ', CNN, ' OBJECT ']); obj = obj | |        {};         if (obj[cnn]) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' node>f ', CNN, ' ARRAY ']); http://forum.jquery.com/topic/ Jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-childif (!OBJ[CNN].         Length) obj[cnn] = Myarr (obj[cnn]); OBJ[CNN] = Myarr (obj[cnn]);         obj[cnn][Obj[cnn].length] = Parsexml (CN, true/* Simple */);        Obj[cnn].length = Obj[cnn].length;         } else{/*dbg*///if (window.console) console.log ([' x2j ', nn, ' node>g ', CNN, ' Dig deeper ... ');        OBJ[CNN] = Parsexml (CN);       };      };     }); };//node.childnodes.length>0};//node.childnodes if (node.attributes) {if (NODE.ATTRIBUTES.Length>0) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' ATTRIBUTES ', node.attributes]) att = {}; obj = O BJ | |      {};       $.each (node.attributes, function (a,at) {var atn = Jsvar (at.name), ATV = At.value;       ATT[ATN] = ATV;        if (Obj[atn]) {/*dbg*///if (window.console) console.log ([' x2j ', nn, ' attr> ', ATN, ' ARRAY ']); http://forum.jquery.com/topic/ Jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child//if (!obj[atn        ].length) Obj[atn] = Myarr (Obj[atn]);//[obj[ATN]];        OBJ[CNN] = Myarr (obj[cnn]); obj[atn][obj[atn].length] = ATV;       Obj[atn].length = Obj[atn].length;        } else{/*dbg*///if (window.console) console.log ([' x2j ', nn, ' attr> ', ATN, ' TEXT ']);       OBJ[ATN] = ATV;      };      });     obj[' attributes ' = att;  };//node.attributes.length>0};//node.attributes if (obj) {obj = $.extend ((txt!= '? New String (TXT): {}),/* {text:txt},*/obj | | {}/*, att ||     {}*/); txt = (obj.text)? (typeof (Obj.text) = = ' object '? Obj.text: [Obj.text | |     "]). Concat ([txt]): txt;     if (txt) obj.text = txt;    txt = ";    }; var out = obj | |    txt    Console.log ([Extended, simple, out]);     if (extended) {if (txt) out = {};//new String (out); txt = Out.text | | TXT | |     '';     if (txt) out.text = txt;    if (!simple) out = Myarr (out);    };   return out; };//parsexml//Core Function End//Utility functions var Jsvar = Function (s) {return String (s | | "). Replace (/-/g," _ ");   }; NEW isnum function:01/09/2010//Thanks to Emile Grau, Gigatecnologies s.l., www.gigatransfer.com, WWW.MYGIGAMAIL.COMFU Nction Isnum (s) {//Based on utility function Isnum from Xml2json plugin (http://www.fyneworks.com/-[email protected ]//few bugs corrected from original function://-Syntax Error:regexp.test (string) instead of String.test (REG)//-RE Gexp modified to accept comma as decimal mark (Latin syntax:25,24)//-RegExp modified to REject if no number before decimal mark: ". 7" is not accepted//-string was "trimmed", allowing to accept space at the Ginning and end of Stringvar regexp=/^ ((-)? ( [0-9]+] ([[\.\,]{0,1}] ([0-9]+)])/return (typeof s = = "number") | | Regexp.test (String (s && typeof s = = "string")? Jquery.trim (s): ");};/ /Old Isnum function: (for reference only)//var Isnum = function (s) {return (typeof s = = "number") | | String (s && typeof s = = "string")? s: '). Test (/^ ((-)? ( [0-9]*) ((\.{ 0,1}) ([0-9]+))? ($)/);   }; var Myarr = function (o) {//http://forum.jquery.com/topic/ JQUERY-JQUERY-XML2JSON-PROBLEMS-WHEN-SIBLINGS-OF-THE-SAME-TAGNAME-ONLY-HAVE-A-TEXTNODE-AS-A-CHILD//IF (! o.length) o = [O];    O.length=o.length; if (!$.isarray (o)) o = [O];   o.length=o.length;//Here's where you can attach additional functionality, such as searching and sorting ... return o;   }; Utility functions End//### PARSER LIBRARY End/Convert Plain Text to XML if (typeof xml== ' string ') xml = $.text2xml (XML);   Quick fail if not XML (or if the is a node) if (!xml.nodetype) return;      if (Xml.nodetype = = 3 | | xml.nodetype = = 4) return xml.nodevalue; Find XML root node var root = (Xml.nodetype = = 9)?      Xml.documentElement:xml;      Convert XML to json var out = Parsexml (root, True/*/simple */); clean-up memory XML = NULL;      root = null;  Send output return out; },//Convert text to XML DOM text2xml:function (str) {///-note:i ' d like-to-use jquery for this, but jquery makes a   ll tags uppercase//return $ (XML) [0];   var out; try{var xml = ((!$.support.opacity &&!$.support.style))? New ActiveXObject ("Microsoft.XMLDOM"): New Domparser (    );   Xml.async = false;   }catch (e) {throw new Error ("XML Parser could not be instantiated")};    try{if ((!$.support.opacity &&!$.support.style)) out = (Xml.loadxml (str))? Xml:false;   else out = xml.parsefromstring (str, "text/xml"); }catch (e) {throw new error ("ErrorParsing XML string ")};  return out; } }); Extend $}) (JQuery);
Written by others, need to use the jquery library, usage $.xml2json ()


JavaScript XML string converted 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.