@H_404_4@
我在
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>@H_404_4@
解决方法
在
XSLT 2.0/
XPath 2.0使用
the standard XPath 2.0 function tokenize().
在XSLT 1.0中,需要编写递归调用的模板,或者更方便地使用str-split-to-words
的str-split-to-words
函数/模板.
以下是后者的一个例子:
<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参数允许指定多个分隔符.在上面的示例中,任何分隔字符可以是逗号,空格或换行符.
@H_404_4@ @H_404_4@