Ankush Patil
Ankush Patil

Reputation: 58

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

Suppose, if I have "Test1|Test2|Test3" as a string and I want compare it with following:

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

Is it possible to check in apply template is it true of false?

Thanks

Upvotes: 1

Views: 297

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117073

I would suggest you take precaution and use:

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

Otherwise you may get false positives - for example, if your string is:

Test1|Test25|Test301

a simple contains() test will also pass all of these:

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

Upvotes: 1

Sebastien
Sebastien

Reputation: 2714

Something like this:

<?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>

See it working here : https://xsltfiddle.liberty-development.net/3Mvnt3H

Upvotes: 1

Related Questions