<?xml version="1.0" encoding="Shift_JIS" ?>

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

<xsl:variable name="width">200px</xsl:variable>
<xsl:variable name="height">200px</xsl:variable>
<xsl:variable name="viewBox">0 0 200 200</xsl:variable>
<xsl:variable name="cx">100</xsl:variable>
<xsl:variable name="cy">100</xsl:variable>
<xsl:variable name="r">80</xsl:variable>

<!--支出項目を、費目をキーにして取り出しておく-->
<xsl:key name="outgo" match="//line[@type='outgo']" use="@group"/>

<xsl:template match="/">
   <svg width="{$width}" height="{$height}" viewBox="$viewBox">

      <!--全支出合計-->
      <xsl:variable name="sum" select="sum(//@amount[../@type='outgo'])"/>

      <svgcg:circle cx="{$cx}" cy="{$cy}" r="{$r}">
         <!--費目ごとに-->
         <xsl:for-each select=
            "//line[generate-id(.)=generate-id( key('outgo', @group ) )]"
         >
            <!-- この費目の支出合計を計算 -->
            <xsl:variable name="group" select="@group"/>
            <xsl:variable name="group-sum"
               select="sum( ../line/@amount[../@type='outgo'
               and ../@group=$group] )"/>
            <xsl:element name="svgcg:arc">
               <xsl:if
                  test="position()!=last()"
               >
                  <xsl:attribute name="angle">
                     <xsl:value-of
                        select="round($group-sum * 360 div $sum)"/>
                  </xsl:attribute>
               </xsl:if>
               <xsl:attribute name="color">
                  <xsl:choose>
                     <xsl:when test="
                        position()=last()"
                     >
                        purple
                     </xsl:when>
                     <xsl:when test=
                     "position() mod 4 = 0">
                        blue
                     </xsl:when>
                     <xsl:when test=
                     "position() mod 4 = 1">
                        red
                     </xsl:when>
                     <xsl:when test=
                     "position() mod 4 = 2">
                        green
                     </xsl:when>
                     <xsl:when test=
                     "position() mod 4 = 3">
                        yellow
                     </xsl:when>
                  </xsl:choose>
               </xsl:attribute>
            </xsl:element>
         </xsl:for-each>
      </svgcg:circle>
   </svg>
</xsl:template>

</xsl:stylesheet>

