After parsing a large XML DOM Object using jQuery's $.parseXML
function, I have a JavaScript DOM Object. My goal is to create a regular JavaScript Object with a specific structure:
{
name: 'my_tree',
children: [
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child_folder',
children: [
{
name: 'child_folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
},
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child_folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
}
]
}
]
}
The original XML structure would resemble something like the following:
<my_tree>
<hello></hello>
<wat></wat>
<child_folder>
<child_folder>
<hello></hello>
<wat></wat>
</child_folder>
<hello></hello>
<wat></wat>
<child_folder>
<hello></hello>
<wat></wat>
</child_folder>
</child_folder>
</my_tree>
Although I attempted to accomplish this with code snippet provided below, it did not yield the desired outcome:
function xmlDomToObject(domObject) {
var result = {children: []};
for (var i = 0; i < domObject.length; i++) {
if (domObject[i].nodeName == "#text") {
continue;
}
result['name'] = domObject[i].nodeName;
result['children'].push(xmlDomToObject(domObject[i].childNodes));
}
return result;
}
var xmlObject = xmlDomToObject(xmlDomObject.childNodes);