Search code examples
xsltxpathxslt-1.0xqueryxslt-2.0

How to print even/odd number using XSLT function (User Defined Function)


Here i'm trying to create user defined function and identify the even/odd numbers please any one can help us.

Note# we want create separate functions for even and odd numbers

XML INPUT

<?xml version="1.0" encoding="UTF-8"?>
<root>
<num>1</num>
<num>2</num>
<num>3</num>
<num>4</num>
<num>5</num>
<num>6</num>
<num>7</num>
<num>8</num>
<num>9</num>
<num>10</num>
</root>

EXPECTED OUTPUT

<?xml version="1.0" encoding="UTF-8"?>
<root>
<even>
    <num>2</num>
    <num>4</num>
    <num>6</num>
    <num>8</num>
    <num>10</num>
</even>
<odd>
    <num>1</num>
    <num>3</num>
    <num>5</num>
    <num>7</num>
    <num>9</num>
</odd>
</root>

Solution

  • You can idenfify even numbers by the expression:

    not($number mod 2)
    

    This returns true() if the number is even, false() otherwise.


    Achieving the output you show is trivial using:

    <xsl:template match="/root">
        <root>
            <even>
                <xsl:copy-of select="num[not(. mod 2)]"/>
            </even>
            <odd>
                <xsl:copy-of select="num[boolean(. mod 2)]"/>
            </odd>
        </root>
    </xsl:template>