我想根据它的计数使用xsl:variable和loop,但我不确定它是否可能在Xslt中.例如,如果我有一个变量名称计数
<xsl:variable name="count" as="xs:integer" select="4"/>
Run Code Online (Sandbox Code Playgroud)
我可以在下面的表格中使用变量!!!
<xsl:if test="some condition"/>
loop from 0 to $count
...do something here
end loop
</xsl:if>
Run Code Online (Sandbox Code Playgroud)
可能吗?
我的输入XML:
<Root>
<Element>
<Value>1</Value>
<Value>2</Value>
</Element>
<Element>
<Value>1</Value>
<Value>2</Value>
<Value>3</Value>
<Value>4</Value>
</Element>
<Element>
<Value>1</Value>
</Element>
</Root>
Run Code Online (Sandbox Code Playgroud)
平面文件中的预期输出是(带换行符):
1,2,,
1,2,3,4
1,,,
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏.谢谢......
使用XSLT 2.0,解决方案可能是:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="count" select="4" />
<xsl:template match="Element">
<xsl:value-of select="for $i in 1 to $count return concat(Value[$i], '')"
separator="," />
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
注意:您也可以使用if语句而不是concat函数.
为了完整起见,使用XSLT 1.0编写的解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="count" select="4" />
<!-- Ignore all text elements -->
<xsl:template match="text()" />
<xsl:template match="Element">
<xsl:if test="$count > 0">
<!-- Output existing values -->
<xsl:apply-templates select="Value[position() <= $count]" />
<!-- Output remaining commas -->
<xsl:call-template name="print-commas">
<xsl:with-param name="number"
select="$count - count(Value)" />
</xsl:call-template>
<!-- Line break -->
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:template>
<!-- Print the first value without a comma preprended to the value -->
<xsl:template match="Value[1]">
<xsl:value-of select="." />
</xsl:template>
<!-- Print the reamaining value with a comma preprended to the value -->
<xsl:template match="Value">
<xsl:value-of select="concat(',', .)" />
</xsl:template>
<!-- Print the given amount of commas -->
<xsl:template name="print-commas">
<!-- Number of commas to be printed -->
<xsl:param name="number" />
<xsl:if test="$number > 0">
<xsl:text>,</xsl:text>
<!-- Recursive call decrementing the number of commas to
be printed -->
<xsl:call-template name="print-commas">
<xsl:with-param name="number"
select="$number - 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)