XSL transformation - XML data to HTML table

前端 未结 1 869
小蘑菇
小蘑菇 2020-12-22 08:15

Is there way how to create a XSL stylesheet for this type a XML document for output like HTML table on the picture below? The problem is, that generated datas are stored ran

相关标签:
1条回答
  • 2020-12-22 08:48

    You should be able to do this pretty easily by:

    1. Grouping by track (using xsl:for-each-group).
    2. Keeping track of what columns need to be output.

    Example...

    XSLT 2.0

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <!--Keep track of all CPU columns.-->
      <xsl:variable name="cols" as="item()*">
        <xsl:variable name="init" 
          select="distinct-values(//sample[starts-with(@label,'cpu')]/@label)"/>
        <xsl:perform-sort select="$init">
          <xsl:sort order="ascending" data-type="text"/>
        </xsl:perform-sort>
      </xsl:variable>
    
      <xsl:template match="/*">
        <html>
          <body>
            <table>
              <thead>
                <tr>
                  <th>Time</th>
                  <xsl:for-each select="$cols">
                    <th><xsl:value-of select="upper-case(replace(.,'_',' '))"/> (%)</th>
                  </xsl:for-each>             
                </tr>
              </thead>
              <tbody>
                <xsl:for-each-group select="sample" group-by="@time">
                  <xsl:sort select="@time" order="ascending" data-type="number"/>
                  <tr>
                    <td>
                      <xsl:value-of select="current-grouping-key()"/>
                    </td>
                    <xsl:for-each select="$cols">
                      <td>
                        <xsl:value-of select="current-group()[@label=current()]"/>
                      </td>
                    </xsl:for-each>
                  </tr>
                </xsl:for-each-group>
              </tbody>
            </table>
          </body>
        </html>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Output

    <html>
       <body>
          <table>
             <thead>
                <tr>
                   <th>Time</th>
                   <th>CPU 0 (%)</th>
                   <th>CPU 1 (%)</th>
                   <th>CPU 2 (%)</th>
                </tr>
             </thead>
             <tbody>
                <tr>
                   <td>1</td>
                   <td>28</td>
                   <td>21</td>
                   <td>4</td>
                </tr>
                <tr>
                   <td>14</td>
                   <td>22</td>
                   <td>52</td>
                   <td>6</td>
                </tr>
             </tbody>
          </table>
       </body>
    </html>

    See fiddle here: http://xsltfiddle.liberty-development.net/eiQZDbp

    0 讨论(0)
提交回复
热议问题