문제

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?

도움이 되었습니까?

해결책

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>        
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top