Link to home
Start Free TrialLog in
Avatar of dbrownell83
dbrownell83

asked on

need help with simple recursive DOM parsing

Hi experts,

I have been looking through the archives, and almost have a solution to my problem, but not really.  The purpose is to fill a YAHOO treeview with my XML data.  In the code below, doc is a well formed XML document.


var rootNode=doc.documentElement;
this.readChildrenIntoTree(rootNode.childNodes, tree.getRoot());
tree.draw();
            
            readChildrenIntoTree:function(nodeList, treeNode) {
               for (x in nodeList)
               {
                 alert(x.nodeValue);
               var tmpNode = new YAHOO.widget.TextNode(x.nodeValue, treeNode, false);
                    
                  if(nodeList.hasChildNodes)
                      readChildrenIntoTree(nodeList.childNodes, tmpNode);
               }
            }

The alert says "undefined", which is quite certainly related to the problem.  How can I get the <x>nodeValue</x>?
And is my recursive code looking more or less correct?

Thanks
Dan





ASKER CERTIFIED SOLUTION
Avatar of hbz
hbz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jessegivy
Nice catch hbz,

The for loop you had was foremed poorly, syntax not javascript.  The "undefined" was printing because you didn't declare x as a variable, so the script couldn't find a variable called x.

Best Wishes,

Jesse
Avatar of dbrownell83
dbrownell83

ASKER

thanks, i copied someone's js code thinking it was some special foreach syntax.  oops.

            readChildrenIntoTree:function(nodeList, treeNode) {
               for (var x=0; x < nodeList.length; x++)
               {
                 var node = nodeList[x];
                     alert(node);
                 alert(node.nodeValue);
                   alert(node.nodeName);
                   var tmpNode = new YAHOO.widget.TextNode(node, treeNode, false);
                    
                  if(node.hasChildNodes)
                      readChildrenIntoTree(node.childNodes, tmpNode);
               }
            }

This prints out:
node = [object Element]
node.nodeValue = null
node.nodeName = "child"

Hmm...
my XML has this sort of look:
<categories>
<child>Engineering
          <child>AeroSpace Engineering</child>
          <child>Computer Engineering</child>
          <child>Electrical Engineering</child>
</child>
</categories>

Does it matter that my inner nodes have the same tag as the outer ones?
erm yeah...  it isnt properly formed.  i'll ask on the xml board.  thanks

thank you for the points!

you should know, however, that for...in *IS* valid syntax in JS, for example "for (var i in arrayList)".   the nodelist object doesn't happen to support it.

- hbz