Created
August 30, 2018 17:48
-
-
Save wbhob/b7ca7ec73538b5673c1e3115762d9380 to your computer and use it in GitHub Desktop.
Parses XML into JSON
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
// 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