This is my XML:
<summary>
<test>
<name>test1</name>
<status>failure</status>
</test>
<test>
<name>test2</name>
<status>success</status>
</test>
<test>
<name>test3</name>
<status>success</status>
</test>
</summary>
If <status> is success, I need to store the position() of <test> node in a variable and fetch it from the next template. I only need the position() of the first match. Is that possible?
I recommend to use a global variable that holds the wanted position:
Because this variable is global (child of
<xsl:stylesheet>), it can be referenced from any template without the need for recalculation within the template:When this sample transformation is applied on the provided XML document:
the position is accessed from within any template (in this case we have a single template) and output correctly:
In case if the XML document’s structure is unknown/unpredictable, and can have any level of nesting, including nested
testelements, then use:Do note: It is wrong to use expressions like the following in order to find the first
testelement the string value of whosestatuschild is"success":In your case the
//pseudo-operator isn’t necessary at all, as the structure of the XML document is statically known and more efficient XPath expressions can be used.//test[status='success'][1]in general may select more than one element. It selects anytestelement the string value of whosestatuschild is"success"and which is the first child of its parent. This is one of the most FAQ in XPath. Remember: The XPath[]operator has higher precedence (priority) than the//pseudo-operator. In case you really must use//(for example the exact structure of the XML document is not known in advance), then the proper XPath to select the first such element is::
As in many other programming languages (and generally in mathematics) brackets are used to explicitly override the standard operators’ precedence.