[xquery-talk] distance between elements and hierarchical order

Sergio Andreozzi sergio.andreozzi at cnaf.infn.it
Fri Dec 9 03:16:56 PST 2005

Wolfgang Hoschek wrote:
> Both can probably be solved by walking the ancestor axis of the  
> elements towards the root.
> For 2) find the nearest common ancestor, and add up the steps.

for problem 1. (compute the hierarchical level) I've this solution so 
far. It uses the recursion to generate the list of ancestors, then count 

declare function local:ancestors-self($n as node()?) {

   if (empty($n))
   then ()
   else (local:ancestors-self($n/..), $n)


declare function local:Hlevel($n as node()?) as xs:integer{

   count( local:ancestors-self($n) )-1



<?xml version="1.0" encoding="UTF-8"?>

for $A in doc("test.xml")/S/A
return <Result>{ local:Hlevel(($A)[1]) }</Result>


for $A in doc("test.xml")/S/A
return <Result>{ local:Hlevel(($A/B)[1]) }</Result>


for $A in doc("test.xml")/S/A
return <Result>{ local:Hlevel(($A/B/C/G/H)[1]) }</Result>


still working on no.2.


More information about the talk mailing list