如何在应用模板中将字符串与 XSLT1.0 中的数组进行比较

How to compare string with array in XSLT1.0 in apply templates

假设, 如果我有 "Test1|Test2|Test3" 作为字符串 和 我想将其与以下内容进行比较:

<items>
<item>Test1</item>
<item>Test2</item>
<item>Test3</item>
</items>

是否可以检查应用模板是真还是假?

谢谢

像这样:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    
  <xsl:output method="xml" indent="yes"/>
    
  <xsl:variable name="arrayString" select="'Test1|Test2|Test3'"/>

  <xsl:template match="items">
    <xsl:copy>
      <xsl:apply-templates select="item[contains($arrayString,.)]"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="item">
    <xsl:copy>
      <xsl:value-of select="concat('Template_item : ', .)"/>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

看到它在这里工作:https://xsltfiddle.liberty-development.net/3Mvnt3H

我建议您采取预防措施并使用:

<xsl:apply-templates select="item[contains(concat('|', $yourString, '|'), concat('|', ., '|'))]"/>

否则您可能会得到误报 - 例如,如果您的字符串是:

Test1|Test25|Test301

一个简单的 contains() 测试也将通过所有这些:

<item>Test2</item>
<item>Test3</item>
<item>Test30</item>