Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 282
ricosrealm Avatar asked Feb 29 '12 21:02

ricosrealm


People also ask

What is node set in XPath?

A node set is a set of nodes. When you write an XPath expression to return one or more nodes, you call these nodes a node set. For example, if you use the following expression to return a node called title , you will have a set of nodes all called title (assuming there's more than one record).

What is XPath selector?

XPath stands for XML Path Language. It uses a non-XML syntax to provide a flexible way of addressing (pointing to) different parts of an XML document. It can also be used to test addressed nodes within a document to determine whether they match a pattern or not.

What is XPath expression in XML?

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.


1 Answers

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(.)
like image 84
Dimitre Novatchev Avatar answered Oct 16 '22 04:10

Dimitre Novatchev