Skip to content

Instantly share code, notes, and snippets.

@wbhob
Created August 30, 2018 17:48
Show Gist options
  • Save wbhob/b7ca7ec73538b5673c1e3115762d9380 to your computer and use it in GitHub Desktop.
Save wbhob/b7ca7ec73538b5673c1e3115762d9380 to your computer and use it in GitHub Desktop.
Parses XML into JSON
// INPUT XML
const xml =
`<Person>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
<Contact>
<Address>
<Street>1000 East St</Street>
<City>Atlanta</City>
<Zip>30330</Zip>
<Phone>
<Home>12345678990</Home>
<Work>1234567890</Work>
</Phone>
</Address>
</Contact>
</Person>`;
let tags: string[] = [];
let res = '';
let currentDepth = 0;
// replace tag markers
xml.replace(/>(.*)<\/(.*)>/g, '/>')
.replace(/</g, '')
.replace(/>/g, '')
.split('\n')
.map(val => {
val = val.replace(/\s/g, '');
if (val.indexOf('/') == 0) {
return 'CLOSING_TAG';
};
return val;
}).forEach((item) => {
if (item == 'CLOSING_TAG') {
currentDepth--;
} else {
res = res + item.replace('/', '') + ' ' + currentDepth + '\n';
}
if (item.indexOf('/') < 0) {
currentDepth++;
}
})
// OUTPUT result
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment