Skip to content

Instantly share code, notes, and snippets.

@eerohele
Created January 14, 2013 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eerohele/4531924 to your computer and use it in GitHub Desktop.
Save eerohele/4531924 to your computer and use it in GitHub Desktop.
Check whether a file exists with XSLT2 (a Java extension -powered function)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:java="http://www.java.com/"
exclude-result-prefixes="java xs">
<xsl:function name="java:file-exists" xmlns:file="java.io.File" as="xs:boolean">
<xsl:param name="file" as="xs:string"/>
<xsl:param name="base-uri" as="xs:string"/>
<xsl:variable name="absolute-uri" select="resolve-uri($file, $base-uri)" as="xs:anyURI"/>
<xsl:sequence select="file:exists(file:new($absolute-uri))"/>
</xsl:function>
</xsl:stylesheet>
@eerohele
Copy link
Author

Use like this:

<xsl:if test="java:file-exists($filename, base-uri())">
  <!-- ... -->
</xsl:if>

@holmbergius
Copy link

Works beautifully. Thanks!

@emmanouela88
Copy link

Hello,

I am trying to make your suggestion work and I am getting this error:
'Cannot find a script or an extension object associated with namespace 'http://www.java.com/'.'

What I am trying to do is to change from the xsl file to a pdf file. My goal is to see if a url of an image has a file that appears on a blob storage and if not then in it's place to show another image.

Whatever I am trying seems to not work. Do you have any suggestions? Thanks

@eerohele
Copy link
Author

@emmanouela88 this solution only works if your XSLT processor supports Java extension functions (such as the paid versions of Saxon, if I remember correctly).

The XSLT processor you're using likely doesn't (and isn't Java-based, I'm guessing).

I'm afraid I can't suggest an alternative solution, because it's very much dependent on the XSLT processor you're using. If you're on .NET, for example, you can look into using XSLT Extension Objects.

@emmanouela88
Copy link

Oh I see.
Thank you for reaching out, to be honest I was able to just use the onerror command on html img tag and this was able to help me instead of searching the files.

But again thank you for that 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment