Mr Rick
Mr Rick

Reputation: 3

XSLT Row counter excluding Null and Zero

<Rows>
    <Row RowNo="1" Amount="0,0"/>
    <Row RowNo="2" Amount="12"/>
    <Row RowNo="3" Amount=""/>
    <Row RowNo="4" Amount="00"/>
    <Row RowNo="5" Amount="33"/>
    <Row RowNo="6" Amount="0,00"/>
    <Row RowNo="7" Amount="0"/>
    <Row RowNo="8" Amount="00,2"/>
</Rows>

These Row's are my input. I want the output to exclude rows where @Amount is '' or 0. And also not count the row for when @Amount = '' and = 0. Expected result:

<Rows>
    <Row RowNo="1" Amount="12"/>
    <Row RowNo="2" Amount="33"/>
    <Row RowNo="3" Amount="00,2"/>
</Rows> 

How can I do this?

Upvotes: 0

Views: 339

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117073

How about something simple, for a change?

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="/Rows">
    <xsl:copy>
        <xsl:for-each select="Row[translate(@Amount, ',0', '')]">
            <Row RowNo="{position()}" Amount="{@Amount}"/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 0

Vebbie
Vebbie

Reputation: 1695

With your given input, a specific (based on input) solution in XSLT 1.0 can be as following:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <Rows>
        <xsl:for-each select="Rows/Row">
            <xsl:choose>
                <xsl:when test="@Amount != '' and (number(@Amount) * 1) != '0' and translate(@Amount, '0', '') != ','">
                    <xsl:copy>
                        <xsl:attribute name="RowNo">
                            <xsl:value-of select="count(preceding-sibling::*[@Amount != '' and (number(@Amount) * 1) != '0' and translate(@Amount, '0', '') != ',']) + 1" />
                        </xsl:attribute>
                        <xsl:for-each select="@*">
                            <xsl:if test="name() != 'RowNo'">
                                <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>
                            </xsl:if>
                        </xsl:for-each>
                        <xsl:apply-templates select="node()" />
                    </xsl:copy>
                </xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </Rows>
</xsl:template>

Upvotes: 1

Related Questions