gpt4 book ai didi

xml - XST - 使用调用模板的输出作为返回值

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:41 25 4
gpt4 key购买 nike

假设我有一个模板foo,它可以在给定参数的情况下输出一些东西。现在我想将该输出用作我的其他模板 loop 的参数,这样我就可以将输出循环一定次数。我已经尝试了一些东西

    <xsl:call-template name="loop">
<xsl:with-param name="times" select="someParam"/>
<xsl:with-param name="output">
<xsl:call-template name="foo">
<xsl:with-param name="type" select="something"/>
</xsl:call-template>
</xsl:with-param>
</xsl:call-template>

换句话说,output 现在应该包含调用 foo 的输出。 loopfoo 都可以独立工作,但似乎我不能以这种方式嵌套它们。我应该如何做到这一点?提前致谢。

最佳答案

问题出在您没有向我们展示的代码中。这是链接/管道模板的正确方法,尽管我不推荐它(请参阅此答案的末尾),

这个转换:

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

<xsl:template match="/">
<xsl:call-template name="loop">
<xsl:with-param name="times" select="3"/>
<xsl:with-param name="output">
<xsl:call-template name="foo">
<xsl:with-param name="pN" select="5"/>
</xsl:call-template>
</xsl:with-param>
</xsl:call-template>
</xsl:template>

<xsl:template name="loop">
<xsl:param name="times" select="1"/>
<xsl:param name="output" select="2"/>

<xsl:choose>
<xsl:when test="not($times > 0)">
<xsl:value-of select="$output"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="loop">
<xsl:with-param name="times" select="$times -1"/>
<xsl:with-param name="output" select="2*$output"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:template name="foo">
<xsl:param name="pN" select="1"/>

<xsl:value-of select="2*$pN"/>
</xsl:template>
</xsl:stylesheet>

应用于任何 XML(未使用)时,产生所需的正确结果:

80

风格推荐:

尽量避免以这种方式链接模板,因为这会导致代码不可读和不可维护。

将中间结果放入(正确命名的)变量中要好得多。这样不仅代码更具可读性和可维护性,而且任何中间结果都可以重复使用多次,而无需重新评估。

这是相同的转换,但考虑到了推荐的风格要求:

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

<xsl:template match="/">
<xsl:variable name="vTwice">
<xsl:call-template name="twice">
<xsl:with-param name="pN" select="5"/>
</xsl:call-template>
</xsl:variable>

<xsl:call-template name="loop">
<xsl:with-param name="pTtimes" select="3"/>
<xsl:with-param name="pN" select="$vTwice"/>
</xsl:call-template>
</xsl:template>

<xsl:template name="loop">
<xsl:param name="pTtimes" select="1"/>
<xsl:param name="pN" select="2"/>

<xsl:choose>
<xsl:when test="not($pTtimes > 0)">
<xsl:value-of select="$pN"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="loop">
<xsl:with-param name="pTtimes" select="$pTtimes -1"/>
<xsl:with-param name="pN" select="2*$pN"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:template name="twice">
<xsl:param name="pN" select="1"/>

<xsl:value-of select="2*$pN"/>
</xsl:template>
</xsl:stylesheet>

关于xml - XST - 使用调用模板的输出作为返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com