dgodbee
dgodbee

Reputation: 3

Count nodes with specific child node in XSL

I have some XSL where I need to do a specific operation for each person that has a specific child node, except the last one of that type:

<xsl:for-each select="/FormData/Persons/Person">
                <xsl:if test="MySpecificType">
                    <!--Header-->
                    <xsl:call-template name="Header"/>

                    <!--Body-->
                    <xsl:call-template name="Person"/>
                    <xsl:if test="position() != last()">
                        <!-- Specific logic -->
                    </xsl:if>
                </xsl:if>
            </xsl:for-each>

The test for if posiition() != last only captures if he's not the last person, what I really want to capture is if he is the not the last person of the specific type.

Is there a way to count how many people there are of that have that child node and then check that inside my if instead? Or possibly just foreach over only the people of with this node?

The xml would look something like:

<Person><Name /><SpecificType><OtherInfo /></SpecificType></Person>

The nodes I don't want to capture would not include the SpecificType node.

Upvotes: 0

Views: 518

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117140

I need to do a specific operation for each person that has a specific child node


Is there a way to count how many people there are of that have that child node

Counting nodes is one thing; processing nodes is another.

To count the qualifying nodes, you can do:

<xsl:value-of select="count(/FormData/Persons/Person[MySpecificType]"/>

To process them, do:

<xsl:for-each select="/FormData/Persons/Person[MySpecificType]">
    <!-- do something -->
   <xsl:if test="position() != last()">
        <!-- do something extra -->
    </xsl:if>
</xsl:for-each>

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167716

Use a predicate <xsl:for-each select="/FormData/Persons/Person[MySpecificType]"> instead of the xsl:if.

Upvotes: 1

Related Questions