加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – XSLT – 将逗号分隔文本拆分为HTML的最佳方法

发布时间:2020-12-16 23:26:10 所属栏目:百科 来源:网络整理
导读:我在 XML元素中有一些数据如下所示: item value="category1,category2"Item Name/item 我感兴趣的是value属性.我能够将此属性中包含的数据放入模板中,如下所示: xsl:template name="RenderValues" xsl:param name="ValueList" / xsl:value-of select="$Val
我在 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-wordsstr-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="',&#10;'"/>
        </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参数允许指定多个分隔符.在上面的示例中,任何分隔字符可以是逗号,空格或换行符.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读