Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for a file existence in XSLT?

Tags:

xslt

ant

I would like to check in XSLT whether an HTML file exists or not. How can I do this? I have already tried the file-exists.xsl from here https://gist.github.com/emth/4531924 but it doesn't work for me. I've been trying to get it running for over 2 hours now, but I am stuck. Here's my ant snippet:

<target name="transform">
    <xslt in="/tmp/sample.xml" out="/tmp/out.html" style="/tmp/sample.xsl" />
</target>

and this is my xslt file:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:java="http://www.java.com/">
<xsl:import href="file-exists.xsl"/>
...    
<xsl:if test="java:file-exists('myfile.html', base-uri())">
    <!-- do something here... -->
</xsl:if>
....

Running this with ant I will get the following error:

[xslt] Processing /tmp/sample.xml to /tmp/out.html
[xslt] Loading stylesheet /tmp/sample.xsl
[xslt] : Error! The first argument to the non-static Java function 'fileExists' is not a valid object reference.
[xslt] : Error! Cannot convert data-type 'void' to 'boolean'.
[xslt] : Fatal Error! Could not compile stylesheet
[xslt] Failed to process /tmp/sample.xml

Can anybody provide me a running example or is there any other alternative? Thanks!

like image 969
user1613270 Avatar asked Nov 27 '13 13:11

user1613270


People also ask

How do I validate an XSLT file?

For this you need a schema-aware XSLT processor that does static checking (for example Saxon-EE), and you need the stylesheet to (a) import the schema using xslt:import-schema, and (b) to invoke validation on the result elements using [xsl:]validation="strict".

What is current () XSLT?

XSLT current() Function The current() function returns a node-set that contains only the current node. Usually the current node and the context node are the same.

Can we use XQuery in XSLT?

For example, you can use XQuery to extract data from an XML database, and XSLT to present the results to users on the web.


2 Answers

I've found a solution:

<xsl:when test="fs:exists(fs:new('myfile.html'))" xmlns:fs="java.io.File">
    <!-- do something here... -->
</xsl:when>

and it works independently of XSLT 1.0 or 2.0

like image 67
user1613270 Avatar answered Sep 30 '22 22:09

user1613270


If the file is a text file, you can use the XSLT 2.0 function:

fn:func-unparsed-text-available()

The fn:unparsed-text-available function determines whether a call on the fn:unparsed-text function with identical arguments would return a string. The function will attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no invalid characters.

This is similar to fn:doc-available() which works on XML documents instead.

like image 42
Sean B. Durkin Avatar answered Sep 30 '22 22:09

Sean B. Durkin