Thursday, 12 September 2013

recursively adding xml elements to a database

recursively adding xml elements to a database

I'm trying to create a multidimensional array from xml code, in the format
[element type, children], so that it creates a value and a reference to
child nodes, if there are any.
so if my xml looked like this:
<name>
<firstName>Mary</firstName>
</name>
my database array would look like this:
[name, firstName] and if you looked at firstName you would see: [Mary
(Youngest)]
So using my limited knowledge of recursive functions and DOM methods, I
came up with this code:
function buildDatabase(nodesAtLevel)
{
//ignore this code
alert(nodesAtLevel.length);
//if the element is a dead end
if (nodesAtLevel.length == 0 && nodesAtLevel[0].nextChild.length == 0)
//return the child node
{
youngestChild = new Array(nodesAtLevel.nodeName + "
(Youngest)", nodesAtLevel[0].firstChild.data);
return youngestChild;
}
//if this element has children
for (var i = 0; i < nodesAtLevel.length; i++)
{
//add the name of the element and its children to the array
var children = new Array(nodesAtLevel.nodeName,
nodesAtLevel[i].childNodes);
//return the array ,
buildDatabase(children);
}
}
And here's the function that tests it:
function test()
{
//load the document
var document = loadXMLDoc("testXML.xml");
elements = document.childNodes;
//give the database object to buildDatabase
database = buildDatabase(elements);
}
I keep getting "nodesAtLevel[i] is undefined"
So the problem statement seems to be this line:
var children = [nodesAtLevel.nodeName, nodesAtLevel[i].childNodes];
My logic is that if an element has multiple children, it will go through
each element of the array, and if that element is a reference to another
variable it will treat that as an array as well to continue down the tree.

No comments:

Post a Comment