Skip to content

Instantly share code, notes, and snippets.

@btray77
Last active April 15, 2021 23:56
Show Gist options
  • Select an option

  • Save btray77/5264672 to your computer and use it in GitHub Desktop.

Select an option

Save btray77/5264672 to your computer and use it in GitHub Desktop.

Revisions

  1. btray77 revised this gist Mar 28, 2013. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions xml2json.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,8 @@
    // Original from: http://killzonekid.com/worlds-smallest-fastest-xml-to-json-javascript-converter/
    // Thanks to Loamhoof for helping get this working!
    // http://stackoverflow.com/questions/15675352/regex-convert-xml-to-json/15680000
    //Load XML into XML variable



    var regex = /(<\w+[^<]*?)\s+([\w-]+)="([^"]+)">/;
  2. btray77 revised this gist Mar 28, 2013. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion xml2json.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    //Load XML into XML variable
    // Original from: http://killzonekid.com/worlds-smallest-fastest-xml-to-json-javascript-converter/
    //Load XML into XML variable


    var regex = /(<\w+[^<]*?)\s+([\w-]+)="([^"]+)">/;
  3. btray77 created this gist Mar 28, 2013.
    27 changes: 27 additions & 0 deletions xml2json.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    //Load XML into XML variable


    var regex = /(<\w+[^<]*?)\s+([\w-]+)="([^"]+)">/;
    while (xml.match(regex)) xml = xml.replace(regex, '<$2>$3</$2>$1>');
    xml = xml.replace(/\s/g, ' ').
    replace(/< *\?[^>]*?\? *>/g, '').
    replace(/< *!--[^>]*?-- *>/g, '').
    replace(/< *(\/?) *(\w[\w-]+\b):(\w[\w-]+\b)/g, '<$1$2_$3').
    replace(/< *(\w[\w-]+\b)([^>]*?)\/ *>/g, '< $1$2>').
    replace(/(\w[\w-]+\b):(\w[\w-]+\b) *= *"([^>]*?)"/g, '$1_$2="$3"').
    replace(/< *(\w[\w-]+\b)((?: *\w[\w-]+ *= *" *[^"]*?")+ *)>( *[^< ]*?\b.*?)< *\/ *\1 *>/g, '< $1$2 value="$3">').
    replace(/< *(\w[\w-]+\b) *</g, '<$1>< ').
    replace(/> *>/g, '>').
    replace(/"/g, '\\"').
    replace(/< *(\w[\w-]+\b) *>([^<>]*?)< *\/ *\1 *>/g, '"$1":"$2",').
    replace(/< *(\w[\w-]+\b) *>([^<>]*?)< *\/ *\1 *>/g, '"$1":[{$2}],').
    replace(/< *(\w[\w-]+\b) *>(?=("\w[\w-]+\b)":\{.*?\},\2)(.*?)< *\/ *\1 *>/, '"$1":{}$3},').
    replace(/],\s*?".*?": *\[/g, ',').
    replace(/< \/(\w[\w-]+\b)\},\{\1>/g, '},{').
    replace(/< *(\w[\w-]+\b)[^>]*?>/g, '"$1":{').
    replace(/< *\/ *\w[\w-]+ *>/g, '},').
    replace(/\} *,(?= *(\}|\]))/g, '}').
    replace(/] *,(?= *(\}|\]))/g, ']').
    replace(/" *,(?= *(\}|\]))/g, '"').
    replace(/ *, *$/g, '');
    xml = '{' + xml + '}';