Ritesh
Ritesh

Reputation: 1143

XSLT find whether sibling exist or not

Sample XML is given below.

<mapNode>
      <mapNode>...</mapNode>
      <mapNode>...</mapNode>-----I am here at 2
      <mapNode>...</mapNode>
      <mapNode>...</mapNode>
</mapNode>
<mapNode>
      <mapNode>...</mapNode>
      <mapNode>...</mapNode>
</mapNode>

I want to know whether position 3 exist or not. Please help me.

Thanks in advance.

Upvotes: 7

Views: 16311

Answers (3)

Tim C
Tim C

Reputation: 70618

If you want to test if an element has a sibling following it, you can use the sensibly named "following-sibling" xpath expression:

<xsl:if test="following-sibling::*" />

Note that this will test if there is any following-sibling. If you only wanted to test for mapNode elements, you could do this

<xsl:if test="following-sibling::mapNode" />

However, this would also be true also in the following case, because following-sibling will look at all following siblings:

<mapNode> 
   <mapNode>...</mapNode> 
   <mapNode>...</mapNode>-----I am here at 2 
   <differentNode>...</differentNode> 
   <mapNode>...</mapNode> 
</mapNode>

If you therefore want to check the most immediately following sibling was a mapNode element, you would do this:

<xsl:if test="following-sibling::*[1][self::mapNode]" />

Upvotes: 22

hielsnoppe
hielsnoppe

Reputation: 2869

In addition to @rene's answer you could also use the following-sibling axis from within any mapNode:

<xsl:template match="mapNode">
    <xsl:if test="count(following-sibling::mapNode)>0">
    <!-- has a successor -->
    </xsl:if>
</xsl:template>

Upvotes: 2

rene
rene

Reputation: 42444

Not knowing what you already have but assuming you have a template to select a toplevel mapNode you can use count to findout how many mapNodes there are under thecurrent node:

   <xsl:template match="/root/mapNode">
      <xsl:if test="count(mapNode)>2">
        more than two mapNodes
      </xsl:if>
    </xsl:template>

Upvotes: 0

Related Questions