Search code examples
xslttypescontain

XSL condition to check if node exists


I want to check if in my XML exists node that has type attribute containing string type_attachment_.

Is it a correct way to check it?

<xsl:if test="count(*[contains(@Type, 'type_attachment_')]) &gt; 0">
   something
</xsl:if>

I don't know how nested can this node be. It can be for example as simple as that:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"?>

<hello-world>
 <greeter>
  <dsdsds>An XSLT Programmer
   <greeting type = 'type_attachment_'>Hello, World!
   </greeting>
  </dsdsds>
 </greeter>
</hello-world>

but can also contain this node nested in different other elements.


Solution

  • Expressions that match existing nodes are truthy. Expressions that do not match any nodes are falsy.

    Therefore, you don't need to count the set of nodes returned. Simply test to see if anything matches.

    <xsl:if test="*[contains(@Type, 'type_attachment')]">
       something
    </xsl:if>