mnvbrtn
mnvbrtn

Reputation: 568

How to output only few nodes

I have the xml coming in as follows.

<Result>
    <customer>
        <id>123</id>
        <lastName>John1</lastName>
        <firstName>Doe1</firstName>
        <phone>1234578900</phone>
    </customer>
    <customer>
        <id>456</id>
        <lastName>John2</lastName>
        <firstName>Doe2</firstName>
        <phone>1234587900</phone>
    </customer>
    <customer>
        <id>789</id>
        <lastName>John3</lastName>
        <firstName>Doe3</firstName>
        <phone>1234467900</phone>
    </customer>
    <customer>
        <id>012</id>
        <lastName>John4</lastName>
        <firstName>Doe4</firstName>
        <phone>1236567900</phone>
    </customer>
    <customer>
        <id>235</id>
        <lastName>John5</lastName>
        <firstName>Doe5</firstName>
        <phone>1232567900</phone>
    </customer>
    <customer>
        <id>568</id>
        <lastName>John6</lastName>
        <firstName>Doe6</firstName>
        <phone>1237567900</phone>
    </customer>
</Result>

I need to output only 5 customer results. If the request has less than 5 customers then i need to output all. but if the request has more than 5 I need to output only 5 results. How to achieve this with stylesheet

Output:

<Result>
    <customer>
        <id>123</id>
        <lastName>John1</lastName>
    </customer>
    <customer>
        <id>456</id>
        <lastName>John2</lastName>
    </customer>
    <customer>
        <id>789</id>
        <lastName>John3</lastName>
    </customer>
    <customer>
        <id>012</id>
        <lastName>John4</lastName>
    </customer>
    <customer>
        <id>235</id>
        <lastName>John5</lastName>
    </customer>
</Result>

Upvotes: 0

Views: 42

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116993

This is rather trivial:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Result">
    <xsl:copy>
        <xsl:for-each select="customer[position() &lt;= 5]">
            <xsl:copy>
                <xsl:copy-of select="id | lastName"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions