Reputation: 1973
I want to throw an exception if one tag doesn't contain an attribute.
Upvotes: 32
Views: 20198
Reputation: 7980
Use xsl:message
with terminate="yes"
to achieve effect similar to throwing an exception:
<xsl:if test="(your condition)">
<xsl:message terminate="yes">ERROR: Missing attribute XYZ under
<xsl:value-of select="local-name()"/> !</xsl:message>
</xsl:if>
This causes the message to be sent to STDERR and terminate processing.
BTW. this is heavily used in Schematron validation.
Upvotes: 37
Reputation: 243449
In addition to the correct answer of using <xsl:message terminate="yes"/>
:
In XSLT 3.0 one can use the new instructions <xsl:try ...>
and <xsl:catch ...>
: http://www.w3.org/TR/xslt-30/#try-catch
In XSLT 2.0 one can also use the standart XPath function error()
to terminate the processing.
Here is an example of using xsl:try
and xsl:catch
:
<xsl:result-document href="out.xml">
<xsl:variable name="result">
<xsl:call-template name="construct-output"/>
</xsl:variable>
<xsl:try>
<xsl:copy-of select="$result" validation="strict"/>
<xsl:catch>
<xsl:message>Warning: validation of result document failed:
Error code: <xsl:value-of select="$err:code"/>
Reason: <xsl:value-of select="$err:description"/>
</xsl:message>
<xsl:sequence select="$result"/>
</xsl:catch>
</xsl:try>
</xsl:result-document>
Upvotes: 26
Reputation: 12154
XSLT isn't meant for validation! it is meant for transformation .. (well XSLT stands for EXtensible Stylesheet Language Transformation)
If you want to validate hierarchy (that is your requirement) and validate the data .. then go for XSD! Extensible Schema Definition..
here is a link reference to learn XSD
XML has to be validated against the XSD by the host code (C#, Java etc) The validation returns set of results. Success or fail with validation errors (if exist)..
Upvotes: 2