【问题标题】:Every loop should repeat twice in xslt每个循环都应该在 xslt 中重复两次
【发布时间】:2022-06-10 18:03:09
【问题描述】:

基本上我需要一个接一个地重复每个子循环两次。在下面的例子中 'apple' 应该重复两次,然后 'mango' 应该重复两次

XML:

<?xml version="1.0" encoding="Windows-1252" standalone="no"?>
<root >
    <child id="123">
        <fruit>apple</fruit>
        <comment>This is 1st line</comment>
    </child>         
   <child id="345">
        <fruit>mango</fruit>
        <comment>This is 2nd line</comment>
    </child>
</root>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="1.0">
    <xsl:output indent="yes" />
    

    <xsl:template match="/">
<xsl:param name="pack" select="2"></xsl:param>

    <xsl:for-each select="root/child">
<xsl:for-each select="(//node())[position() &lt;= $pack]">
        
<xsl:text>&#xA;</xsl:text>
        <xsl:value-of select="//fruit"/>

          
         <xsl:text>&#xA;</xsl:text>
       <xsl:value-of select="//comment"/>
<xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
</xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

当前操作:


苹果 这是第一行

苹果 这是第一行

苹果 这是第一行

苹果 这是第一行


预期:


苹果 这是第一行

苹果 这是第一行

芒果 这是第二行

芒果 这是第二行


非常感谢您的帮助!

【问题讨论】:

  • 你的逻辑不清楚:pack参数是否表示child数据重复多少次?
  • yes pack参数表示循环重复多少次
  • 您是否仅限于 XSLT 1.0?

标签: xml loops xslt iteration


【解决方案1】:

XSLT 1.0 中,您需要执行以下操作:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:param name="pack" select="2"/>

<xsl:template match="child" name="repeat">
    <xsl:param name="times" select="$pack"/>
    <xsl:if test="$times > 0">
        <xsl:value-of select="fruit"/>
        <xsl:text>&#xA;</xsl:text>
        <xsl:value-of select="comment"/>
        <xsl:text>&#xA;</xsl:text>
        <xsl:call-template name="repeat">
            <xsl:with-param name="times" select="$times - 1"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2019-01-01
    相关资源
    最近更新 更多