How to use recursion to buid a tree from an xml file?

O

openleren

Hi all,

The aim is to convert xml elements into simple but nested divs using a
RECURSIVE function:

-read an element
-construct a DIV for it
-read its nodeName and nodeValue
-see if it has any element children and do the same for them

Imagine an simple xml doc personen.xml:
===================================
<?xml version="1.0" encoding="UTF-8"?>
<personen>
<persoon>
<voornaam>Jan</voornaam>
<naam>Vandorpe</naam>
</persoon>
<persoon>
<voornaam>Pol</voornaam>
<naam>Ampe</naam>
</persoon>
</personen>
====================================

What I want to get would be exact the same structure, but 2 x 3 nested divs

I've managed to do this using document.writes and opening and closing the
divs on the right spot, but I fail miserably using .appendChild.
The script starts from a hyperlink that calls the importXML function with
the "personen.xml" argument.
It provides for Mozilla but that part doesn't work as well, it only works in
IE, don't know why as well, but that's not the issue here.

It produces all the nodes in div's behind each other, not INSIDE each other.
I should be able to return the node with a div appended but I fail.
Who can help?

========================================================
<script language="JavaScript">
<!--
function importXML(file)
{
if (document.implementation && document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = maakLijst;
}
else if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.onreadystatechange = function () {if (xmlDoc.readyState == 4)
maakLijst()};
}
else
{
alert('Your browser can\'t handle this script');
return;
}
xmlDoc.load(file);
}

var begin;

function maakLijst(){
var personen = xmlDoc.getElementsByTagName('personen');
var hook = document.getElementById('hook');

bouwOp(personen[0]);
hook.appendChild(begin);
}

//recursive sub?

function bouwOp(noot){
if(!begin||begin==null){
begin=document.createElement('div')
}
if (noot.nodeType==1) {
var dief = document.createElement('div');
var nootNaam = noot.nodeName;
if (noot.firstChild.nodeType==3) {
nootInhoud = noot.firstChild.nodeValue;
}
var nootInhoud = document.createTextNode(nootNaam+' : '+nootInhoud);
dief.appendChild(nootInhoud);
for (var i=0; i<noot.childNodes.length;i++){
bouwOp(noot.childNodes(i))
}
begin.appendChild(dief)
}
}
-->
</script>
=========================================


thanks for any help, Jan vandorpe
openleren @ skynet.be
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top