1

Given

<nodeList>
    <crazyNode>Data to be overwrited</crazyNode>
    <simpleNode>Normal data</simpleNode>
    <crazyNode>Actual data</crazyNode>
</nodeList>

I want to get the last crazyNode (the one which contains Actual data).

I know how to access the first node, for example:

nodeList.crazyNode[0]

And I guess a solution would be

nodeList.crazyNode[nodeList.crazyNode.length() - 1]

But for some reason I don't like doing that, too verbose and maybe there's a method more elegant.

Thanks

Jorjon
  • 5,316
  • 1
  • 41
  • 58

2 Answers2

1

You could refactor the code to be more readable, but that is the way to do it. Since the problem itself is getting the actual index, you could just declare a new variable to hold that value, like so:

var lastCrazyNodeIndex: int = nodeList.crazyNode.length() - 1;

You can then write a method for getting the last item, here's an idea:

public function getLastCrazyNode(nodeList:XML):Object
{
    var lastCrazyNodeIndex: int = nodeList.crazyNode.length() - 1;

    if( lastCrazyNodeIndex != -1 )
        return nodeList[ lastCrazyNodeIndex ];

    return null;
}

Even if it's the same idea, it's more readable.

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
1

You could use something like:

nodeList.crazyNode.(childIndex()==length()-1);

Though it may not be any "prettier"...

Corey
  • 5,818
  • 2
  • 24
  • 37