0

I have a list of currency codes that I need to use to create currency pairs. Below is a (simplified) example

<?xml version="1.0" encoding="UTF-8"?>
 <CurrencyLists>
  <Currency>USD</Currency>
  <Currency>BRL</Currency>
  <Currency>EUR</Currency>
  <Currency>GBP</Currency>
 </CurrencyLists>

I'm trying to match each currency to the others to create a pair (cartesian product) like this USDBRL, USDEUR, USDGBP, BRLUSD, BRLEUR, BRLGBP, EURUSD, EURBRL, EURGBP (you get the idea)

I can loop in xslt and get each value but I'm not sure how to get the values a second time here is my sample xslt code

<xsl:template match="/">

    <CurrencyPairs>
     <Total>
         <xsl:value-of select="count(CurrencyLists/Currency)"></xsl:value-of>
     </Total>
    <xsl:for-each select="CurrencyLists/Currency">

    <!--<CurrencyPair><xsl:value-of select="."/></CurrencyPair>-->
        <xsl:variable name="first" select="."/>
        <first><xsl:value-of select="$first"/></first>

       <!-- nested loop / cartesian here -->                


    </xsl:for-each>

    </CurrencyPairs>
</xsl:template>

if I add a second for-each in the middle, I do not get any output. I searched here but didn't see anything that was relevant. I'm trying to make something that allows for more currency codes to be added (like JPY, CHF, THB) without having to create the pairs/cartesian product by hand (which is what I'm doing now)

thanks!

2 Answers 2

1

You can do so fairly simply, like this:

  <xsl:template match="/">
    <CurrencyPairs>
      <xsl:variable name="allCurrencies" select="CurrencyLists/Currency" />

      <Total>
        <xsl:value-of select="count($allCurrencies)"></xsl:value-of>
      </Total>

      <xsl:for-each select="$allCurrencies">
        <xsl:variable name="first" select="."/>

        <xsl:for-each select="$allCurrencies[. != $first]">
          <CurrencyPair>
            <First>
              <xsl:value-of select="$first" />
            </First>
            <Second>
              <xsl:value-of select="." />
            </Second>
          </CurrencyPair>
        </xsl:for-each>        
      </xsl:for-each>
    </CurrencyPairs>
  </xsl:template>
Sign up to request clarification or add additional context in comments.

1 Comment

perfect! that works. Thank you very much. I'm not sure what I was doing that it wasn't visible. I have the nested loop working though
0

Inside the for-each you can certainly have another one with an absolute path <xsl:for-each select="/CurrencyLists/Currency"> or with a relative to the one of the outer for-each, e.g. <xsl:for-each select="../Currency">.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.