Search code examples
xmlxsltvalue-of

Is it possible to force XSLT transformation to fail if an element does not exist?


We are using XSLT stylesheets to extract data from a large XML file and write it to a CSV file.

The code to write out the value to CSV typically looks like this:

...
<xsl:value-of select="$quote"/>
<xsl:value-of select="pbs:code"/>
<xsl:value-of select="$quote"/>
<xsl:value-of select="$delimiter"/>
...

I would really like the transformation to fail if the input XML is not in the expected format. Is there any way to force the transformation to fail if there are elements missing (i.e. elements that the stylesheet is expecting)?


Solution

  • There are two possibilities to check whether an element is present:

    • One is <xsl:fallback> to check if an element in the XSL is invalid (useful for version-checking)
    • The other is <xsl:message> to check if an element in the XML is invalid.

    In your case the second variant will be the best choice.
    So use <xsl:message> with the attribute terminate="yes" like this:

    ...
    <xsl:if test="not($qoute)">
      <xsl:message terminate="yes">
        ERROR: $quote is not present!
      </xsl:message>
    </xsl:if>
    <xsl:value-of select="$quote"/>
    ...
    

    This will break the XSLT-transformation with the given error message if $quote is not a valid element.