tags:

views:

22

answers:

1

I have a transverse tree written in JSP which goes through an XML file.

When I get to a certain Text Node, I'd like to be able to search back up the tree to find a certain element associated with that node.

I'm thinking I need to do a For loop and use some kind of 'getLastNode' or 'getParentNode' function. Would this be the correct method? I'm a little unsure of the syntax, so any help would be much appreciated!

I did a bit of search and I can't find anything which demonstrates what I'm trying to do nor can I find a list of the functions I'm after.

A: 

You need to keep calling getParentNode until you hit a node matching your criteria. For example:

public Node searchUpFor(String tagToFind, Node aNode) {
    Node n = aNode.getParentNode();
    while (n != null && !n.getNodeName().equals(tagToFind)) {
        n = n.getParentNode();
    }
    return n;
}
dogbane
Be careful though, this code can return null if it goes up the tree and doesn't find what its you're looking for.
Shynthriir
@dogbane thanks for that. I'm using a switch with cases, can I code in under the text node case and leave out the "public Node", etc or should I call that separately?
Hammer
It's not necessary to define a new method, but I would recommend it especially if you are going to be using this in other parts of your code. It will work ok directly in your switch statement too.
dogbane