recursive Method

Hi all,

i try to implement a recursive Method, that will traverse a Tree (no binary tree).

The tree is the representation of an XML Document that was parsed with the JDOM-Api (Sax-Parser)

I want to step through all nodes and all childs of this nodes recursivly to find an element with a special Attribute. this element shpould be returned, else null.

This is what i have now:

public Element getReferencedElement(Element element, String elementID)

{

if(element.getAttribute("DEF") !=null)

{

if(element.getAttributeValue("DEF").compareTo(elementID) == 0)

{

return element;

}

elseif(element.getChildren() ==null)

{

returnnull;

}

else

{

return element.getChild("ElementName");

}

}

else

return getReferencedElement(element.getChild("ElementName"), elementID);

}

This code works. But only on Trees with only one child per node. How do I step over all children? To get a List of all children, you can call getChildren() on the current element.

Many thanks.

[1944 byte] By [Masom17a] at [2007-9-29 6:37:26]
# 1

change this:

else

return getReferencedElement(element.getChild("ElementName"), elementID);

}

to something like this:

else

for(Iterator i = element.getChildren.iterator(); iterator.hasNext();)

{

Element child = (Element) i.next();

Element referenced = getReferencedElement(child);

if (referenced != null) return referenced;

}

return null;

}

dubwaia at 2007-7-14 20:40:00 > top of Java-index,Other Topics,Algorithms...
# 2
Great!This works. I even try to understand it ;-)Thanks
Masom17a at 2007-7-14 20:40:00 > top of Java-index,Other Topics,Algorithms...
# 3
> This works. I even try to understand it ;-)THANK YOU! I wish more people would.
cdbennetta at 2007-7-14 20:40:00 > top of Java-index,Other Topics,Algorithms...