xsl-list
[Top] [All Lists]

Re: [xsl] RE: Is xsl:for-each "syntactic sugar"?

2010-05-07 18:09:15
On Fri, 2010-05-07 at 18:34 -0400, Costello, Roger L. wrote:
Hi Folks,

Suppose that I want to write an XSLT transform that outputs a bank account 
balance after each debit/credit transaction. Here's an XML document that has 
the start balance followed by each transaction:

<?xml version="1.0"?>
<BankTransactions>
    <StartBalance>100.00</StartBalance>
    <Transaction>-5.00</Transaction>
    <Transaction>-2.50</Transaction>
    <Transaction>10.00</Transaction>
    <Transaction>-7.50</Transaction>
</BankTransactions>

The output should be:

95 92.5 102.5 95

I do not believe that this task can be accomplished using xsl:for-each. Do 
you agree?

No. Wait. Yes, I agree hat you believe that. But I don't agree it's
true :-)

First, here's a non-recursive solution with apply-templates:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
  <xsl:strip-space elements="*"/>
  <xsl:template match="BankTransactions">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="StartBalance"></xsl:template>

  <xsl:template match="Transaction">
    <xsl:value-of select="preceding-sibling::StartBalance +
sum(preceding-sibling::Transaction) + ." />
    <xsl:if test="following-sibling::Transaction">
      <xsl:text> </xsl:text>
    </xsl:if>

  </xsl:template>
</xsl:stylesheet>


Now here's one with for-each

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
  <xsl:strip-space elements="*"/>
  <xsl:template match="BankTransactions">
    <xsl:for-each select="Transaction">
      <xsl:value-of select="preceding-sibling::StartBalance +
sum(preceding-sibling::Transaction) + ." />
      <xsl:if test="following-sibling::Transaction">
        <xsl:text> </xsl:text>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Liam

-- 
Liam Quin - XML Activity Lead, W3C, http://www.w3.org/People/Quin/
Pictures from old books: http://fromoldbooks.org/
Ankh: irc.sorcery.net irc.gnome.org www.advogato.org


--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--