Question

I am not sure if I'm really doing a mistake or if this is just not working properly:

<xsl:if test="position() = 1 or parent::position() = 1">
   <!-- do something -->
</xsl:if>

If the current node is the first child, or it's parent is the first child, then do something special.

The problem is "parent::position() = 1" .. with .net's XmlCompiledTransform I get

Expected end of the expression, found '('. ...sition() = 1 or parent ::position -->(<-- = 1.

Now, apparently it doesn't like that position() function in the second part, but.. how do I get the parent's position? How do I, generally, combine XPath functions with XPaths in tests?

Was it helpful?

Solution

Good question, +1.

You need to define what is meant by position of the parent.

parent::node()[position() = 1] 

is always true() when the parent node exists (is false() only if the context node is the document node / as this node is the top node in the tree and doesn't have a parent), because any node in a tree (well-formed XML document) by definition can have at most one parent node.

Most likely, you want to test that the parent element is the first in document order among its siblings. One way to test for this is:

not(parent::node()/preceding-sibling::*)

So, the complete code becomes:

<xsl:if test="position() = 1 or not(parent::node()/preceding-sibling::*)">        
   <!-- do something -->        
</xsl:if>        
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top