By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,849 Members | 2,361 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,849 IT Pros & Developers. It's quick & easy.

OO Recursion Help needed

P: 1
Trying to write some javascript code to convert an XML file to DOM elements...and seem to be having trouble with some recursion, here's the code so far:

Expand|Select|Wrap|Line Numbers
  1. function iegObject(xmlFile, domRoot) {
  2.     var that = this;
  3.  
  4.     //AJAX Calls to get xml document from file system
  5.     this.myXMLRequest = new ajaxObject(xmlFile);
  6.     this.myXMLRequest.callback = function(respText, respStat, respXML) {
  7.         that.xmlRoot = respXML.getElementsByTagName("ieg")[0];
  8.         that.traverseXML(that.xmlRoot, that.domRoot);
  9.     };
  10.  
  11.     //xml root node and dom root node, where the former will be used to build the latter. Followed by the call to get the xml using ajax
  12.     this.domRoot = document.getElementById(domRoot);
  13.     this.xmlRoot = null;
  14.     this.myXMLRequest.update();
  15.  
  16.     //Recursive function to build dom from xml
  17.     this.traverseXML = function(xmlRoot, domRoot) {
  18.         this.children = xmlRoot.childNodes;
  19.         this.i;
  20.         for(this.i = 0; this.i < this.children.length; this.i++) {
  21.             domRoot.appendChild(document.createTextNode(this.children[this.i].nodeName));
  22.             domRoot.appendChild(document.createElement("br"));
  23.             if(this.children[this.i].firstChild) {
  24.                 this.traverseXML(this.children[this.i], domRoot);
  25.             }
  26.             alert("ending on " + xmlRoot.nodeName + " with " + this.i + " of " + this.children.length);
  27.         }
  28.         return;
  29.     }
  30. }
it steps into the xml tree properly enough, but when it comes time to return, this.children.length is shown to be 1 (which it is when the deepest call is first returned) at every level, and every recursive call ends without their for loop getting through more than one element.

RESOLVED: Apparenty it was an issue with my variable scope. Used 'var' to clear things up.
Jan 23 '08 #1
Share this Question
Share on Google+
2 Replies


Ganon11
Expert 2.5K+
P: 3,652
Moved to Javascript forum from Miscellaneous Discussions forum.

Ganon11 - MODERATOR
Jan 23 '08 #2

acoder
Expert Mod 15k+
P: 16,027
I see it's resolved, but use of hasChildNodes() would've been useful - see example (further down).
Jan 24 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.