XSLT - 将逗号分隔的文本拆分和呈现为 HTML 的最佳方法 [英] XSLT - Best way to split and render comma separated text as HTML
问题描述
我在 XML 元素中有一些数据,如下所示:
I have some data in an XML element that looks like this:
<item value="category1,category2">Item Name</item>
我感兴趣的是 value 属性.我可以将包含在此属性中的数据放入如下所示的模板中:
The bit I'm interested in is the value attribute. I'm able to get the data contained in this attribute into a template which looks like this:
<xsl:template name="RenderValues">
<xsl:param name="ValueList" />
<xsl:value-of select="$ValueList" /> <!-- outputs category1,category2-->
</xsl:template>
我想要做的是以有效的方式处理逗号分隔值.从 RenderValues 模板内部呈现类似以下内容的最佳方法是什么?
What I want to do is to process the comma separated values in an efficient manner. What is the best way to render something like the following from inside the RenderValues template?
<a href="x.asp?item=category1">category1</a>
<a href="x.asp?item=category2">category2</a>
推荐答案
在 XSLT 2.0/XPath 2.0 使用 标准 XPath 2.0 函数 tokenize().
In XSLT 2.0/XPath 2.0 use the standard XPath 2.0 function tokenize().
在 XSLT 1.0 中,要么需要编写一个递归调用模板,或者更方便的是,使用 str-split-to-words
函数/模板.net" rel="noreferrer">FXSL 库.
In XSLT 1.0 one needs either to write a recursively called template or, more conveniently, use the str-split-to-words
function/template of 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
参数允许指定多个分隔字符.在上面的例子中,任何分隔符都可以是逗号、空格或换行符.
The pDelimiters
parameter of this template allow multiple delimiting characters to be specified. In the above example, any separating character can be either a comma, a space or a new line character.
这篇关于XSLT - 将逗号分隔的文本拆分和呈现为 HTML 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!