Created
August 16, 2013 21:37
-
-
Save mspanish/6253698 to your computer and use it in GitHub Desktop.
From http://stackoverflow.com/questions/15675352/regex-convert-xml-to-json Working XML to JSON regex function in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var regex = /(<\w+[^<]*?)\s+([\w-]+)="([^"]+)">/; | |
while(xml.match(regex)) xml = xml.replace(regex, '<$2>$3</$2>$1>'); // For attributes | |
xml = xml.replace(/\s/g, ' '). // Finds all the white space converts to single space | |
replace(/< *\?[^>]*?\? *>/g, ''). //Finds the XML header and removes it | |
replace(/< *!--[^>]*?-- *>/g, ''). //Finds and removes all comments | |
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>$2'). | |
replace(/< *(\w[\w-]+\b) *</g, '<$1>< '). | |
replace(/> *>/g, '>'). | |
//replace(/< *\/ *(\w[\w-]+\b) *> *< *\1 *>/g, ''). // breaks the output? | |
replace(/"/g, '\\"'). | |
replace(/< *(\w[\w-]+\b) *>([^<>]*?)< *\/ *\1 *>/g, '"$1":"$2",'). | |
replace(/< *(\w[\w-]+\b) *>([^<>]*?)< *\/ *\1 *>/g, '"$1":{$2},'). | |
replace(/< *(\w[\w-]+\b) *>(?=.*?< \/\1\},\{)/g, '"$1":[{'). | |
split(/\},\{/). | |
reverse(). | |
join('},{'). | |
replace(/< *\/ *(\w[\w-]+\b) *>(?=.*?"\1":\[\{)/g, '}],'). | |
split(/\},\{/). | |
reverse(). | |
join('},{'). | |
replace(/< \/(\w[\w-]+\b)\},\{\1>/g, '},{'). | |
replace(/< *(\w[\w-]+\b)[^>]*?>/g, '"$1":{'). | |
replace(/< *\/ *\w[\w-]+ *>/g,'},'). | |
replace(/\} *,(?= *(\}|\]))/g, '}'). | |
replace(/] *,(?= *(\}|\]))/g, ']'). | |
replace(/" *,(?= *(\}|\]))/g, '"'). | |
replace(/ *, *$/g, ''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment