Search code examples
xsltxpathxpath-2.0

XPath: Get root node of a node-set from a specified node


Is it possible to write an XPath expression that gets the root node of a node within a node-set with only a reference to the node?

Using "/" won't work for me because that only refers to the input document root. Also I would like it to work without a context and to use it for a general node-set that may be created dynamically during processing.

For example...

<xsl:function name="my:getRoot">
    <xsl:param name="n" />
    <xsl:variable name="rootnode" select="some_solution($n)"/>
</xsl:function>

Thanks for the help.


Solution

  • In XPath 1.0 use:

    ancestor-or-self::node()[last()]
    

    This selects the most distant of the ancestors of the current node -- which is its document-node.

    In XPath 2.0 use:

     root(.)