Stuff
Stuff

Reputation: 103

XSLT - Determine if value exists in a node with multiple same named nodes

Looking to determine if BBB exists within the XML. I can effectively echo it out as shown below. How can I effective search the PRODUCT_CODE node(s) to determine if BBB exists or NOT within the group?

XML:

<ECOMM_VARS>
  <PRODUCT_CODE>AAA</PRODUCT_CODE>
  <PRODUCT_CODE>BBB</PRODUCT_CODE>
  <PRODUCT_CODE>CCC</PRODUCT_CODE>
</ECOMM_VARS>

XSLT:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="PRODUCT_CODE">
    <xsl:value-of select="concat(., '&#xA;')"/>
  </xsl:template>

  <xsl:template match="text()"/>

</xsl:stylesheet>

Upvotes: 0

Views: 3151

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86744

Test for existence is the result of evaluating an XPath predicate expression in an if or choose:

<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="//PRODUCT_CODE[text()='BBB']">true</xsl:when>
        <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
</xsl:template>

This outputs true if any <PRODUCT_CODE> node's text equals 'BBB'.

Upvotes: 2

zx485
zx485

Reputation: 29022

You can use a predicate on your matching template.
The following example does only match the first time (indicated by [1]) the text of a <PRODUCT_CODE> element matches the string 'BBB'.

<xsl:template match="PRODUCT_CODE[text() = 'BBB'][1]">
  <!-- Only matches the first time 'BBB' occurs -->
  <xsl:value-of select="concat(., '&#xA;')"/>
</xsl:template>

If there do exist one or more <PRODUCT_CODE> elements with 'BBB' text it matches exactly one time.

Upvotes: 1

Related Questions