如何在XSLT中以逗号分隔的列表中提取特定值并将该值与另一个值进行比较?

时间:2012-11-29 21:27:02

标签: xslt

我是XSLT的新手,对Line Break in XSLT for a comma separated value有类似的要求,但我需要做以下事情

  1. 检查值是否为单个字符串,例如苹果或者它是逗号分隔的列表,例如苹果,梨等
  2. 如果是逗号分隔列表,则检查列表是否具有特定值或值
  3. 如果值存在则执行某些操作
  4. 如果是单个字符串,例如Apple然后做点什么
  5. 我如何实现这一点是XSLT 2.0?

1 个答案:

答案 0 :(得分:2)

您可以对列表进行标记。像这样的函数可以完成这项工作(嵌入在工作的XSLT中用于演示目的):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="NS:MY">
  <xsl:function name="my:test">
    <xsl:param name="string"/>
    <xsl:variable name="tokens" select="tokenize(normalize-space($string),'\s*,\s*')"/>
    <xsl:choose>
      <xsl:when test="normalize-space($string)='Apples'">
        Do something where we have a single "Apples" 
      </xsl:when>
      <xsl:when test="normalize-space($string)='Pears'"> 
        Do something where we have a single "Pears" 
      </xsl:when>
      <xsl:when test="$tokens='Apples' and $tokens='Pears'"> 
        There are Apples and Pears 
      </xsl:when>
      <xsl:when test="$tokens='Apples'"> 
        There are Apples in the list 
      </xsl:when>
      <xsl:when test="$tokens='Pears'"> 
        There are Pears in the list 
      </xsl:when>
      <xsl:otherwise> 
        Didn't find what we're looking for 
      </xsl:otherwise>
    </xsl:choose>
  </xsl:function>

  <xsl:template match="/">
    <out>
      <xsl:value-of select="my:test('Apples')"/>
      <xsl:value-of select="my:test('Pears,Oranges')"/>
      <xsl:value-of select="my:test(' Apples ,Pears,Oranges')"/>
      <xsl:value-of select="my:test('Oranges , Bananas, Strawberries')"/>
    </out>
  </xsl:template>
</xsl:stylesheet>

您也可以使用regular expressions

有关normalize-space()tokenize()的操作,请参阅XPath文档。您可能希望用明智的东西替换伪名称“NS:MY”。

相关问题