How do I check for the existence of an external file with XSL?
Asked Answered
L

10

16

I've found a lot of examples that reference Java and C for this, but how do I, or can I, check for the existence of an external file with XSL.

First, I realize that this is only a snippet, but it's part of a huge stylesheet, so I'm hoping it's enough to show my issue.

    <!-- Use this template for Received SMSs -->
<xsl:template name="ReceivedSMS">
    <!-- Set/Declare "SMSname" variable (local, evaluates per instance) -->
    <xsl:variable name="SMSname">
        <xsl:value-of select=" following-sibling::Name"/>
    </xsl:variable>
    <fo:table font-family="Arial Unicode MS" font-size="8pt" text-align="start">
        <fo:table-column column-width=".75in"/>
        <fo:table-column column-width="6.75in"/>
        <fo:table-body>
            <fo:table-row>
                <!-- Cell contains "speakers" icon -->
                <fo:table-cell display-align="after">
                    <fo:block text-align="start">
                        <fo:external-graphic src="../images/{$SMSname}.jpg" content-height="0.6in"/>

What I'd like to do, is put in an "if" statement, surronding the {$SMSname}.jpg line. That is:

                     <fo:block text-align="start">
                        <xsl:if test="exists( the external file {$SMSname}.jpg)">
                            <fo:external-graphic src="../images/{$SMSname}.jpg" content-height="0.6in"/>                            
                        </xsl:if>
                        <xsl:if test="not(exists( the external file {$SMSname}.jpg))">
                            <fo:external-graphic src="../images/unknown.jpg" content-height="0.6in"/>                            
                        </xsl:if>
                    </fo:block>                       

Because of "grouping", etc., I'm using XSLT 2.0. I hope that this is something that can be done. I hope even more that it's something simple.

As always, thanks in advance for any help. LO

Loiseloiter answered 26/5, 2010 at 23:54 Comment(3)
Good question (+1). Short answer: cannot be currently done with pure XSLT 2.0. Long answer and explanation: see my answer. :)Polychaete
It looks like it will be possible with EXPath extensions - file package (expath.org/spec/file)...Troposphere
I have done it for myself, Check my answer for the solution.Cerated
P
11

No, this cannot be done using XSLT 2.0/XPath 2.0.

The XSLT 2.0 function unparsed-text-available() is only suitable for locating text files and even if a text file with the specifies URI exists this function may return false(), because it also must read the contents of the file and check that it only contains allowed characters.

From the spec:

"The unparsed-text-available function determines whether a call on the unparsed-text function with identical arguments would return a string.

If the first argument is an empty sequence, the function returns false. If the second argument is an empty sequence, the function behaves as if the second argument were omitted.

In other cases, the function returns true if a call on unparsed-text with the same arguments would succeed, and false if a call on unparsed-text with the same arguments would fail with a non-recoverable dynamic error.

Note:

This requires that the unparsed-text-available function should actually attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no characters that are invalid in XML "

End of quotation.

Polychaete answered 27/5, 2010 at 1:25 Comment(0)
E
12

For anyone else who might stumble upon this old question, by piecing together information from various sources on the internet, I came up with this XSLT2 function that uses a Java extension for checking whether a file exists:

<?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>

You can then use the function like this:

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

This works at least with Saxon 9.1.0.5J — haven't tested it with any other XSLT processors.

Note: If the file for whose existence you're checking is an XML file and you're using XSLT2, you can also use the built-in doc-available() function:

<xsl:if test="doc-available('hello_world.xml')">
  <!-- ... -->
</xsl:if>
Emphasis answered 14/1, 2013 at 17:53 Comment(2)
With PE9.4, I get the error message Error at xsl:sequence on line 32 column 66 of propertize-opf.xslt: XPST0017 XPath syntax error at char 12 on line 32 near {...xists(file:new($absolute-ur...}: Cannot find a matching 1-argument function named {java.io.File}new(). For diagnostics on calls to Java methods, use the -TJ command line option or set the Configuration property FeatureKeys.TRACE_EXTERNAL_FUNCTIONSTonneson
@torazaburo: Are you sure you're passing base-uri() as the second argument to java:file-exists()? As in: <xsl:if test="java:file-exists($filename, base-uri())"> <!-- ... ---> </xsl:if>. Also, note that this function will only work on XSLT2.0.Emphasis
P
11

No, this cannot be done using XSLT 2.0/XPath 2.0.

The XSLT 2.0 function unparsed-text-available() is only suitable for locating text files and even if a text file with the specifies URI exists this function may return false(), because it also must read the contents of the file and check that it only contains allowed characters.

From the spec:

"The unparsed-text-available function determines whether a call on the unparsed-text function with identical arguments would return a string.

If the first argument is an empty sequence, the function returns false. If the second argument is an empty sequence, the function behaves as if the second argument were omitted.

In other cases, the function returns true if a call on unparsed-text with the same arguments would succeed, and false if a call on unparsed-text with the same arguments would fail with a non-recoverable dynamic error.

Note:

This requires that the unparsed-text-available function should actually attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no characters that are invalid in XML "

End of quotation.

Polychaete answered 27/5, 2010 at 1:25 Comment(0)
E
3

In case someone else needs it and is using fop, I would like to share this answer since it worked for me like a charm.

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

Eyestrain answered 2/9, 2015 at 18:57 Comment(0)
U
2

EDIT: Use unparsed-text-available function. It is part of xslt 2.0, but not XQuery or standalone XPath.

I've left my previous answer here so you can follow the trail of uncertainty...

I don't believe there is a way of doing this in XSLT using the standard functions. You can do it using extension functions, as described here, for java.

There is the unparsed-text-available function, but I'm unsure if this is a standard function. There's an example of it's usage at Zvon. The unparsed-text-available is mentioned here as being part of xslt 2.0, and is supported in Saxon.

Ultravirus answered 27/5, 2010 at 0:2 Comment(0)
R
2

A proposed File Module EXPath specification would support file-system functions such as this (file:exists() in the spec) as standard XPath extension functions. There isn't yet an XSLT implementation for this, but its worth watching.

Rachealrachel answered 27/5, 2010 at 9:19 Comment(2)
This is not working for me below is error: XPath syntax error at char 30 on line 40 in {...file:exists($htmlFilePath))...}: Cannot find a matching 1-argument function named {expath.org/ns/file}exists()Cerated
Is it dependent on saxon version I am using saxon 8 but don't think that would be the case.Cerated
M
1

Back to pgfearo's notice.

A proposed File Module EXPath specification would support file-system functions such as this (file:exists() in the spec) as standard XPath extension functions. There isn't yet an XSLT implementation for this, but its worth watching.

For those who need to check if an file exists or not.

file:exists($path as xs:string)

works fine now.

Millman answered 14/9, 2017 at 12:46 Comment(0)
C
1

If you still wants to do it in XSLT here is the solution, I have done it for myself as explained below.

This will not working with regular java.io.File class in XSLT. So I have used java.nio.file.Files class.

JARS required - servelt.jar w: is the namespace of the our own Java class where pathFromURI method is defined.

Code:

<xsl:variable name="fileURI" select="u:new($absoluteFilePath)" xmlns:u="java:java.net.URI"/>
<xsl:variable name="filePathFromURI" select="w:pathFromURI($fileURI)"/>
<xsl:variable name="fileNotExist" select="not(files:exists($filePathFromURI, /..)) or files:size($filePathFromURI) = 0"/>

public static java.nio.file.Path pathFromURI(java.net.URI uri) throws Exception {
    return java.nio.file.Paths.get(uri);
}
Cerated answered 30/1, 2019 at 7:2 Comment(0)
A
0

It can't solely be done by standard XSLT, you have to use an extention function or some annoying workaround. There are two methods using extension functions: use of standard java/.NET for custom functions (works with some versions of Saxon, AltovaXML, and others), or use of processor specific extension functions, like saxon:file-last-modified()/saxon:last-modified(). You can find some sample code here, look for intern:file-exists().

If you can't use extension functions, you can either generate an XML file externaly which contains informations about your file system and pass it to your stylesheet, or you can wrap binary images within SVG and than use fn:doc-available().

Affiliation answered 5/11, 2011 at 9:0 Comment(0)
A
0

If you need to check for the existence of an XML file, use an external entity and an inline doctype:

<!DOCTYPE foo [ <!ENTITY bar SYSTEM "baz.xml"> ]>

Then add the entity to the stylesheet:

&bar;

The processor will timeout if the file is not found.

If you know the files exist but want to dynamically load one out of many, use the concat function and a choose/when block:

<xsl:variable name="page_name">
<xsl:choose>
  <xsl:when test="$page = 1">
    <xsl:value-of select="'page1.xml'"/>
  </xsl:when>
  <xsl:when test="$page = 2">
    <xsl:value-of select="'page2.xml'"/>
  </xsl:when>
  <!--...-->
  <xsl:when test="$page = 9">
    <xsl:value-of select="'page9.xml'"/>
  </xsl:when>
  <xsl:when test="$page = 10">
    <xsl:value-of select="'page10.xml'"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:value-of select="'page0.xml'"/>
  </xsl:otherwise>
</xsl:choose>
</xsl:variable>

<xsl:variable name="agree" select="document(concat('include/pages/',$page_name))//processing-instruction()"/>

References

Antabuse answered 12/9, 2013 at 6:49 Comment(0)
W
0

For anyone who needs plain XSLT solution for checking if file exist you can just use

unparsed-text-available(concat(system-property('user.dir'),'/filename.text'))

or wrap it into a function

<xsl:function name="functx:file-exists" xmlns:functx="http://www.functx.com">
    <xsl:param name="path"/>
    <xsl:value-of select="unparsed-text-available(concat(system-property('user.dir'),'/',$path))"/>
</xsl:function>

using this unparsed-text-available(concat(system-property('user.dir'),'/filename.text'))=false() will mean that file does not exist.

Have fun!

Wivern answered 27/2, 2020 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.