xslt Format data in a table some columns are blank

2019-03-05 03:22发布

问题:

With XSLT 1.0, how can I change the following:

<root>
  <element id="1" Team="Rangers" Season="2011" Points="12" />
  <element id="2" Team="Rangers" Season="2012" Points="5" />
  <element id="3" Team="Rangers" Season="2013" Points="3" />
  <element id="4" Team="Astros" Season="2011" Points="12" />
  <element id="5" Team="Astros" Season="2013" Points="2" />
</root>

Into:

<table>
    <tr><td>Team</td>
    <td>2011</td>
    <td>2012</td>
    <td>2013</td>
    <td>Total</td></tr>

    <tr><td>Rangers</td>
    <td>12</td>
    <td>5</td>
    <td>3</td>
    <td>20</td></tr>

    <tr><td>Astros</td>
    <td>12</td>
    <td>0</td>
    <td>2</td>
    <td>14</td></tr>
</table>

The heading can be generated manually as it is static, but I am unsure how to handle null data. Any help would be greatly appreciated!

回答1:

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

<xsl:output indent="yes"/>

<xsl:key name="T" match="element" use="@Team"/>
<xsl:key name="S" match="element" use="@Season"/>

<xsl:template match="root">
 <xsl:variable name="years"  select="element[generate-id()=generate-id(key('S',@Season)[1])]"/>
 <table>
  <tbody>
   <tr>
    <td>Team</td>
    <xsl:for-each select="$years">
     <xsl:sort select="@Season"/>
     <td><xsl:value-of select="@Season"/></td>
    </xsl:for-each>
    <td>Total</td>
   </tr>

   <xsl:for-each select="element[generate-id()=generate-id(key('T',@Team)[1])]">
    <tr>
     <xsl:variable name="thisteam" select="key('T',@Team)"/>
     <xsl:for-each select="$years">
      <xsl:sort select="@Season"/>
      <td>
       <xsl:choose>
    <xsl:when test="$thisteam[@Season=current()/@Season]">
     <xsl:value-of select="$thisteam[@Season=current()/@Season]/@Points"/>
    </xsl:when>
    <xsl:otherwise>
     <xsl:value-of select="0"/>
    </xsl:otherwise>
       </xsl:choose>
      </td>
     </xsl:for-each>
     <td><xsl:value-of select="sum($thisteam/@Points)"/></td>
    </tr>
   </xsl:for-each>
  </tbody>
 </table>
</xsl:template>

</xsl:stylesheet>

Produces

       <?xml version="1.0" encoding="utf-8"?>
<table>
   <tbody>
      <tr>
         <td>Team</td>
         <td>2011</td>
         <td>2012</td>
         <td>2013</td>
         <td>Total</td>
      </tr>
      <tr>
         <td>12</td>
         <td>5</td>
         <td>3</td>
         <td>20</td>
      </tr>
      <tr>
         <td>12</td>
         <td>0</td>
         <td>2</td>
         <td>14</td>
      </tr>
   </tbody>
</table>