Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XPath to find the closest ancestor in a ancestor-or-self nodelist

Tags:

xml

xslt

xpath

I have a structure with recurring elements like this:

<a>
  <b>
    <a>
    </a>
  </b>
  <a>
    <b>
       <a>
         <c att="val" />
       </a>
    </b>
  </a>
</a>

Asuming the c-node is the $currentNode, when I use XPath

<xsl:value-of select="($currentNode/ancestor-or-self::a)" />

I get an unordered list of nodes matching the expression. What I need is to always get the node closest up the tree, as in deepest in the branches or the highest @level.

I cannot use XPath 2 max-function like this unfortunately:

<xsl:value-of select="($currentNode/ancestor-or-self::a)[max(@level)]" />

Notice that the closest a-node not always is exactly above the context, just somewhere up there...

Any suggestions appreciated!

Regards Alex

like image 803
Alex Avatar asked Mar 26 '13 19:03

Alex


People also ask

What is an ancestor node in XPath?

Definition of XPath Ancestor. The ancestor axis chooses all of the current node's ancestor elements (parent, grandparent, great-grandparents, and so on). The root node is always present on this axis (unless the current node is the root node).

How do I find the parent of an element in XPath?

Hey Hemant, we can use the double dot (“..”) to access the parent of any node using the XPath. For example – The locator //span[@id=”first”]/.. will return the parent of the span element matching id value as 'first.


1 Answers

I think you get an ordered set of nodes, from parent to ancestor.

Try $currentNode/ancestor-or-self::a[1] to get parent of c att="val".

like image 162
Istao Avatar answered Oct 12 '22 23:10

Istao