1

XSLT 1.0 を使用して、特定のノードの下にあるサブノードを要約しながら、別のノード セットからのデータでコンテンツを洗練された方法で変更するにはどうすればよいでしょうか? 私はこのxmlを持っていると仮定します:

<Root>
    <ExchangeRates>
        <ExchangeRate>
            <CurrencyCode>USD</CurrencyCode>
            <Rate>6.4</Rate>
        </ExchangeRate>
        <ExchangeRate>
            <CurrencyCode>EUR</CurrencyCode>
            <Rate>8.44</Rate>
        </ExchangeRate>
        <ExchangeRate>
            <CurrencyCode>SEK</CurrencyCode>
            <Rate>1</Rate>
        </ExchangeRate>
    </ExchangeRates>
    <Prices>
        <Price>
            <Currency>SEK</Currency>
            <Amount>10000</Amount>
        </Price>
        <Price>
            <Currency>EUR</Currency>
            <Amount>1000</Amount>
        </Price>
        <Price>
            <Currency>USD</Currency>
            <Amount>1000</Amount>
        </Price>
    </Prices>
</Root>

ExchangeRates を使用して SEK に変換されたすべての金額の合計が必要です。結果は次のようになります。

<SumInSEK>24840</SumInSEK>

金額を変換する必要がなければ、単純に xpath sum() 関数を使用します。この場合、その機能を使用することは可能ですか?

4

2 に答える 2

2

これは簡単かもしれないと思いました...しかし、この機会に sum() を使用できるとは思いません...私ができる最善のことは、再帰的なテンプレートです。

    ?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" 
>
  <xsl:key name="rates" match="//ExchangeRate/Rate" use="parent::*/child::CurrencyCode/text()"/>

  <xsl:template match="//Prices">
    <SUmInSEK>
      <xsl:call-template name="sum"/>
    </SUmInSEK>
  </xsl:template>

  <xsl:template name="sum">
    <xsl:param name="iterator" select="1"/>
    <xsl:param name="total" select="0"/>
    <xsl:variable name="price" select="child::Price[$iterator]"/>
    <xsl:variable name="current">
      <xsl:value-of select="number($price/child::Amount) * number( key('rates', $price/child::Currency) )"/>
    </xsl:variable>
    <xsl:variable name="newtotal">
      <xsl:value-of select="$total + $current"/>
    </xsl:variable>
    <xsl:choose>
      <xsl:when test="$price/following-sibling::Price">
        <xsl:call-template name="sum">
          <xsl:with-param name="iterator" select="$iterator+1"/>
          <xsl:with-param name="total" select="$newtotal"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$total + $current"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="* | /">
    <xsl:apply-templates />
  </xsl:template>

  <xsl:template match="text() | @*">
  </xsl:template>

  <xsl:template match="processing-instruction() | comment()" />

</xsl:stylesheet>
于 2013-05-02T15:19:16.557 に答える