我在 XML 元素中有一些数据,如下所示:
<item value="category1,category2">Item Name</item>
我感兴趣的是 value 属性。我能够将此属性中包含的数据放入如下所示的模板中:
<xsl:template name="RenderValues">
<xsl:param name="ValueList" />
<xsl:value-of select="$ValueList" /> <!-- outputs category1,category2-->
</xsl:template>
我想做的是以有效的方式处理逗号分隔值。从 RenderValues 模板内部呈现如下内容的最佳方式是什么?
<a href="x.asp?item=category1">category1</a>
<a href="x.asp?item=category2">category2</a>
最佳答案
在XSLT 2.0/XPath 2.0使用 the standard XPath 2.0 function tokenize() .
在XSLT 1.0 要么需要编写一个递归调用的模板,要么更方便地使用 str-split-to-words
the FXSL library 的功能/模板| .
这是后者的一个例子:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common"
>
<!-- -->
<xsl:import href="strSplit-to-Words.xsl"/>
<!-- -->
<xsl:output indent="yes" omit-xml-declaration="yes"/>
<!-- -->
<xsl:template match="/*">
<xsl:variable name="vwordNodes">
<xsl:call-template name="str-split-to-words">
<xsl:with-param name="pStr" select="string(@value)"/>
<xsl:with-param name="pDelimiters"
select="', '"/>
</xsl:call-template>
</xsl:variable>
<!-- -->
<xsl:apply-templates select="ext:node-set($vwordNodes)/*"/>
</xsl:template>
<!-- -->
<xsl:template match="word" priority="10">
<a href="x.asp?item={.}"><xsl:value-of select="."/></a>
</xsl:template>
<!-- -->
</xsl:stylesheet>
当上述转换应用于提供的 XML 文档时:
<item value="category1,category2">Item Name</item>
产生了想要的结果:
<a href="x.asp?item=category1" xmlns:ext="http://exslt.org/common">category1</a>
<a href="x.asp?item=category2" xmlns:ext="http://exslt.org/common">category2</a>
此模板的pDelimiters
参数允许指定多个定界字符。在上面的示例中,任何分隔符都可以是逗号、空格或换行符。
关于xml - XSLT - 将逗号分隔文本拆分和呈现为 HTML 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/584082/