Kevin
Kevin

Reputation: 1143

How to check value exists in XSLT

I have some xml like this;

<formErrors>
    <value>address_1</value>
    <value>address_2</value>
//.. etc

And in an XSL template I have $formErrors as a variable and I want to check if a value exists. If there was a PHP equivalent, I would want an in_array() function. How can I do this in XSLT?

Upvotes: 5

Views: 20858

Answers (2)

FailedDev
FailedDev

Reputation: 26940

Try this :

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:variable name="check">address_1</xsl:variable>
    <xsl:if test="count(/formErrors[value/text() = $check]) > 0">
      <xsl:message terminate="no">Value with text <xsl:value-of select="$check"/> : exists!</xsl:message>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Output :

[xslt] : Warning! Value with text address_1 : exists!

Upvotes: 1

a1ex07
a1ex07

Reputation: 37382

<xsl:if test="count(formErrors/value) > 1"> 
    Show Errors
</xsl:if>
<!-- Test if value exists -->
<xsl:if test="formErrors/value ='address_1'"> 
    Show Errors
</xsl:if>

Upvotes: 7

Related Questions