tags:

views:

338

answers:

3

If one is using the document function and opening up files that might not exist e.g.

<xsl:variable name="input" select="document($A)/document/input"/>

what is the graceful way of handling the error? I would like a default value for the variable if the file can't be opened.

A: 

The graceful way would be to check file existence before you feed the parameter to your stylesheet.

Tomalak
It is not really coming from the command line, I just wrote the question that way to make it simple. (I agree with your comment if it was.) :-)It seems like their must be some way of "handling errors" such as this with xslt.
Atlas1j
+1  A: 

I believe you can write your <xsl:variable> like so:

<xsl:variable name="input">
 <xsl:choose>
  <xsl:when test="document($A)/document/testElementCondition = 'foo'">
   <xsl:value-of select="document($A)/document/input" />
  </xsl:when>
  <xsl:otherwise>
   <!-- add some default source document and logic that will then direct to an error message. -->
  </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

It is too bad that you often have to result to hacks to get things done in XSL.

Elijah
As pointed out in my answer, there is no guarantee that the XSLT Processor will not raise an error (which is allowed by the XSLT Spec.)Therefore, the above is not a completely correct answer.
Dimitre Novatchev
+1  A: 

There isn't a general way to handle gracefully an error in the document() function.

According to the XSLT 1.0 spec:

" If there is an error retrieving the resource, then the XSLT processor may signal an error; if it does not signal an error, it must recover by returning an empty node-set. "

This means that we are at the mercy of the implementor whether an empty node-set is produced by the function (good, we can test for empty (non-existent) node-set) or "signals an error", which typically may end the transformation.

In case we have checked that a particular implementation of a specific XSLT processor only produces an empty node-set and does not end the transformation, we may decide to test for this condition and "gracefully" recover. However, our application becomes non-portable, it depends on this specific XSLT processor and there is absolutely no guarantee that in the next version this behaviour will not change to the worse one. Risky, isn't it?

Therefore, it is best that whoever launches the transformation (such as from within a C# program), should check for the existence of the file and pass an appropriate parameter to the transformation, reflecting this existence.

Dimitre Novatchev