首页 > 解决方案 > 使用 XSLT 填充垂直列数据

问题描述

我是 XSLT 的新手,我的 XML 在下面

<Aus>
  <au>
     <ele>
        <auid>Au1</auid>
        <cid>C1</cid>
        <fn>F1</fn>
        <sn>S1</sn>
        <dept>D1</dept>
     </ele>
     
     <ele>
        <auid>Au2</auid>
        <cid>C2</cid>
        <fn>F2</fn>
        <sn>S2</sn>
        <dept>D2</dept>
     </ele>
     
     <ele>
        <auid>Au3</auid>
        <cid>C3</cid>
        <fn>F3</fn>
        <sn>S3</sn>
        <dept>D4</dept>
     </ele>..............
  </au>
</Aus>

我想要使​​用 XSLT 转换的 html 视图中的如下输出 在此处输入图像描述

但是 XSLT 代码应该很容易通过位置增量来识别下一列。请帮我。

我目前的代码是

<xsl:for-each select="//Aus/au">
<table>
<tr>
<td><xsl:value-of select="ele[1]/auid"/></td><td><xsl:value-of select="ele[2]/auid"/></td><td><xsl:value-of select="ele[3]/auid"/></td>
</tr>
<tr>
<td><xsl:value-of select="ele[1]/cid"/></td><td><xsl:value-of select="ele[2]/cid"/></td><td><xsl:value-of select="ele[3]/cid"/></td>
</tr>
..........
</table>
</xsl:for-each>

标签: htmlxmlxslt

解决方案


我会这样做:

  <xsl:template match="Aus/au">
      <table>
          <tbody>
              <xsl:apply-templates select="ele[1]/*" mode="row"/>
          </tbody>
      </table>
  </xsl:template>
  
  <xsl:template match="ele/*" mode="row">
      <tr>
          <xsl:variable name="pos" select="position()"/>
          <xsl:apply-templates select="../../ele/*[$pos]"/>
      </tr>
  </xsl:template>
  
  <xsl:template match="ele/*">
      <td>
          <xsl:value-of select="."/>
      </td>
  </xsl:template>

https://xsltfiddle.liberty-development.net/gVhEaiK

您在评论中链接的示例似乎有更复杂的输入数据,因为它似乎有嵌套元素,而且似乎有很多没有数据的元素;然而,模板可以适应例如

  <xsl:template match="authorDetails/authors">
      <table>
          <tbody>
              <xsl:apply-templates 
                select="element[1]/descendant::*[not(*)]" mode="row"/>
          </tbody>
      </table>
  </xsl:template>
  
  <xsl:template match="element//*" mode="row">
      <tr>
          <th>
              <xsl:value-of select="local-name()"/>
          </th>
          <xsl:variable name="pos" select="position()"/>
          <xsl:apply-templates select="ancestor::authors/element/descendant::*[not(*)][$pos]"/>
      </tr>
  </xsl:template>
  
  <xsl:template match="element//*">
      <td>
          <xsl:value-of select="."/>
      </td>
  </xsl:template>

示例:https ://xsltfiddle.liberty-development.net/gVhEaiK/5


推荐阅读