Skip to content

Instantly share code, notes, and snippets.

@petersirka
Created June 7, 2014 20:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save petersirka/9e79b1d43cf6e579fc62 to your computer and use it in GitHub Desktop.
Save petersirka/9e79b1d43cf6e579fc62 to your computer and use it in GitHub Desktop.
/**
* Simple XML parser
* @param {String} xml
* @return {Object}
*/
function parseXML(xml) {
var beg = -1;
var end = 0;
var tmp = 0;
var current = [];
var obj = {};
var from = -1;
while (true) {
beg = xml.indexOf('<', beg + 1);
if (beg === -1)
break;
end = xml.indexOf('>', beg + 1);
if (end === -1)
break;
var el = xml.substring(beg, end + 1);
var c = el[1];
if (c === '?' || c === '/') {
var o = current.pop();
if (from === -1 || o !== el.substring(2, el.length - 1))
continue;
var path = current.join('.') + '.' + o;
var value = xml.substring(from, beg);
if (typeof(obj[path]) === 'undefined')
obj[path] = value;
else if (obj[path] instanceof Array)
obj[path].push(value);
else
obj[path] = [obj[path], value];
from = -1;
continue;
}
tmp = el.indexOf(' ');
var hasAttributes = true;
if (tmp === -1) {
tmp = el.length - 1;
hasAttributes = false;
}
from = beg + el.length;
var isSingle = el[el.length - 2] === '/';
var name = el.substring(1, tmp);
if (!isSingle)
current.push(name);
if (!hasAttributes)
continue;
var match = el.match(/\w+\=\".*?\"/g);
if (match === null)
continue;
var attr = {};
var length = match.length;
for (var i = 0; i < length; i++) {
var index = match[i].indexOf('"');
attr[match[i].substring(0, index - 1)] = match[i].substring(index + 1, match[i].length - 1);
}
obj[current.join('.') + (isSingle ? '.' + name : '') + '[]'] = attr;
}
return obj;
};
@SilentCicero
Copy link

SilentCicero commented Apr 3, 2017

Do you have tests for this? @petersirka

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment