从逗号分隔字符串 [XML/XSL] 创建选择下拉列表



我正在开发一个运行非常旧版本的ASPDotNetStoreFront的传统电子商务网站,完全免责声明我不精通XML/XSL,我只需要深入研究并尝试通过查看其他代码来使代码工作。

从本质上讲,某些产品在销售数量上受到限制。产品页面以逗号分隔的字符串 .e.g 的形式接收此内容

"5,10,15,20"

我在下面设置了一个参数来收集这些数据,它可以正常工作

<xsl:param name="restrictedquantities">
<xsl:value-of select="/root/Products2/Product/RestrictedQuantities" />
</xsl:param>     

由此,我需要将数量作为选择标签中的单独选项输出,如下所示

<select>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>

我已经设法让它 98% 使用以下代码,我从其他堆栈溢出问题中找到的大部分代码,并一直在尝试将其修补在一起,

<xsl:when test="$restrictedquantities != ''">
<select>
<xsl:call-template name="split">
<xsl:with-param name="s" select="$restrictedquantities" />
</xsl:call-template>
</select>
</xsl:when>

然后在下面的模板之外,我创建了另一个模板,该模板通过逗号拆分字符串,当它输出时,我在值周围放置标签。

<xsl:template name="split" xmlns="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="s" />
<xsl:param name="withcomma" select="false()" />
<xsl:choose>
<xsl:when test="contains($s, ',')">
<!-- if there is still a comma, call me again
with everything after the first comma... -->
<xsl:call-template name="split">
<xsl:with-param name="s" select="substring-after($s, ',')" />
<xsl:with-param name="withcomma" select="true()" />
</xsl:call-template>
<!-- ...and print afterwards the current part -->
&lt;option value="<xsl:value-of select="substring-before($s, ',')" />"&gt;<xsl:value-of select="substring-before($s, ',')" />&lt;/option&gt;
</xsl:when>
<xsl:otherwise>
<!-- No comma left in the remaining part: print the rest -->
&lt;option value="<xsl:value-of select="$s" />"&gt;<xsl:value-of select="$s" />&lt;/option&gt;
</xsl:otherwise>
</xsl:choose>
</xsl:template>

这导致下面的输出,它似乎在我的模板输出周围输出双引号,使其损坏。

我的选择标签的控制台输出 我想我需要以某种方式逃避我的代码,但我不确定。我觉得我正在强迫 XSL 做一些它不应该做的事情。

任何帮助或替代方案都很棒 谢谢

这可能是由于您尝试创建option标签的方式令人困惑

&lt;option value="<xsl:value-of select="substring-before($s, ',')" />"&gt;<xsl:value-of select="substring-before($s, ',')" />&lt;/option&gt;

您在此处输出文本,而不是创建新元素。你真的应该这样做...

<option value="{substring-before($s, ',')}"><xsl:value-of select="substring-before($s, ',')" /></option>

请注意在创建属性时使用属性值模板(大括号(。

另请注意,您也不需要"拆分"模板上的xmlns="http://www.w3.org/1999/XSL/Transform"。事实上,如果你现在把它留在里面,它会导致错误,因为这意味着处理器会把option当作一个xsl元素,并抱怨因为它没有识别它。

无论如何,请尝试此模板

<xsl:template name="split">
<xsl:param name="s" />
<xsl:param name="withcomma" select="false()" />
<xsl:choose>
<xsl:when test="contains($s, ',')">
<xsl:call-template name="split">
<xsl:with-param name="s" select="substring-after($s, ',')" />
<xsl:with-param name="withcomma" select="true()" />
</xsl:call-template>
<option value="{substring-before($s, ',')}"><xsl:value-of select="substring-before($s, ',')" /></option>
</xsl:when>
<xsl:otherwise>
<option value="{$s}"><xsl:value-of select="$s" /></option>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

最新更新