Mr. Atria,
You left out a key element from the answer you got from stack overflow.
Note that Dimitre's response used a filter expression
(path expression) [predicate]
not a simple path expression
The ()s are critical.
$test//child/ancestor-or-self::test[ last() ]
is very different from
($test//child/ancestor-or-self::test)[ last() ]
The ancestor axis is a reverse axis, but when the xpath expression is
complete, the sequence of nodes are then put in document order
regardless of what order the last axis had.
In any event, I don't understand what is wrong with simply
$test/ancestor::element()[1]
Perhaps I don't understand your question (which is simpler than the
Stack Overflow question you linked to). But if you are just looking
for the nearest ancestor element, then it seems that
$test/ancestor::element()[1] should give it to you.