zl程序教程

您现在的位置是:首页 >  其他

当前栏目

用XSL(正确方式)中的3个TD生成每个TR?

2023-04-18 12:30:49 时间

我只需要每行有3个产品。每个产品都在模板“OneProduct”(不包括)中,而推杆大多数Table标签都在此表格之外。以下实际上可行,但它是如何以正确的方式完成的?用XSL(正确方式)中的3个TD生成每个TR?

<xsl:if test="(position() mod 3) = 1"> 
    <xsl:text disable-output-escaping="yes"> 
    <![CDATA[<TR name="PROD_ROW">]]> 
    </xsl:text> 
</xsl:if> 

    <TD width="33%" align="center" name="PRODUCT_CELL"> 

    <xsl:call-template name="OneProduct"> 
     <xsl:with-param name="productId" select="$productId" /> 
    </xsl:call-template> 

    </TD> 

<xsl:if test="((position()+1) mod 3 = 1)"> 
    <xsl:text disable-output-escaping="yes"> 
     <![CDATA[</TR>]]> 
    </xsl:text> 
</xsl:if> 

Ichi San

没有看到您的输入XML和预期输出XML,很难弄清楚您正在做什么。 –

对不起吉姆..下次我肯定会收录一些资料..谢谢。 –

回答

在回答你的问题,这不是首选的方式。这是你可以用程序语言来做的事情;迭代递增计数器的元素,然后在到达第3,第6等元素时输出分隔元素。但XSLT是一种功能性语言,需要采用不同的方法。

你可以做的是使用xsl:apply-templates来选择每一行中第一个元素。假设你有一些这样的XML

<products> 
    <product id="1" name="Product 1" /> 
    <product id="2" name="Product 2" /> 
    <product id="3" name="Product 3" /> 
    <product id="4" name="Product 4" /> 
    <product id="5" name="Product 5" /> 
</products> 

那么你XSL:申请模板会是这样的:

<xsl:apply-templates select="product[position() mod 3 = 1]" /> 

在匹配的产品元素的模板,你会再选择该行中的所有元素(即,在当前元素,加上两个以下的元素)

<xsl:apply-templates 
    select="self::*|following-sibling::product[position() &lt; 3]" mode="cell" /> 

请注意这里使用的模式,因为您将有两个匹配产品的模板,您需要区分它们。

最后,你只需要这个“单元格”模板来输出产品。

<xsl:template match="product" mode="cell"> 
    <td> 
     <xsl:value-of select="@name" /> 
    </td> 
</xsl:template> 

担心是,如果你没有细胞每行的一个确切的数字(例如,在这个例子中有五种款产品,所以最后一排只有两个单元的唯一的事情。

尝试使用以下XSLT

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

<xsl:template match="/*"> 
    <table> 
     <xsl:apply-templates select="product[position() mod 3 = 1]" /> 
    </table> 
</xsl:template> 

<xsl:template match="product"> 
    <tr> 
     <xsl:apply-templates select="self::*|following-sibling::product[position() &lt; 3]" mode="cell" /> 
    </tr> 
</xsl:template> 

<xsl:template match="product" mode="cell"> 
    <td> 
     <xsl:if test="position() &lt; 3 and not(following-sibling::product[1])"> 
      <xsl:attribute name="colspan"> 
       <xsl:value-of select="4 - position()" /> 
      </xsl:attribute> 
     </xsl:if> 
     <xsl:value-of select="@name" /> 
    </td> 
</xsl:template> 
</xsl:stylesheet> 

用XSL(正确方式)中的3个TD生成每个TR?