Search code examples
xsltxslt-2.0

get information on attachments to use in the output like file size


I need to translate a link like <a ref="123.pdf"> to a link where the filesize is present, like <a ref="123.pdf" size="22Kb">. The pdf's are present in the folder that contains the inputfile. Is there a way to do that with xslt 2.0? Can someone point me in the right direction?

Thanks!


Solution

  • Assuming you can use the commercial editions (i.e. PE or EE) of Saxon 9 or any other XSLT 2.0 processor that supports the EXPath file module you can use it as follows:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:file="http://expath.org/ns/file"
        exclude-result-prefixes="xs file"
        version="2.0">
    
        <xsl:template match="@* | node()">
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="a/@href[file:exists(resolve-uri(., base-uri()))]">
            <xsl:copy/>
            <xsl:attribute name="size" select="concat(file:size(resolve-uri(., base-uri())) idiv 1024, 'KB')"/>
        </xsl:template>
    
    </xsl:stylesheet>
    

    Using Saxon that transforms

    <root>
        <a href="test2016082601.pdf">doc</a>
    </root>
    

    into

    <root>
        <a href="test2016082601.pdf" size="141KB">doc</a>
    </root>