Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a txt file from disk and inline the content using XSTL?

Tags:

xslt

xslt-2.0

I have an xslt and I need to read a file from disk. The file is a simple text file which I would like to read the full content and inline it in my output html/pdf file. Is this possible?

like image 637
code-gijoe Avatar asked Dec 01 '25 14:12

code-gijoe


1 Answers

Here's how it can be done, using XSLT 2.0's unparsed-text() function:

D:\MiLu\Dev\XML :: more > eins.txt
Ich bin die eins.
^Z

D:\MiLu\Dev\XML :: more > zwei.txt
Ich bin die zwei.
^Z

D:\MiLu\Dev\XML :: saxon unparsed-text.xml unparsed-text.xsl
<?xml version="1.0" encoding="UTF-8"?>
<eins>
   <zwei> bla </zwei>
   <drei>Ich bin die eins.&#xD;
&#xD;
</drei>
   <vier>Ich bin die zwei.&#xD;
&#xD;
</vier>
</eins>

D:\MiLu\Dev\XML :: more /t1 unparsed-text.xml
<eins>
 <zwei> bla </zwei>
 <drei>
  <textfile href="eins.txt"/>
 </drei>
 <vier>
  <textfile href="zwei.txt"/>
 </vier>
</eins>

D:\MiLu\Dev\XML :: more /t1 unparsed-text.xsl
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:strip-space elements="*"/>
 <xsl:output method="xml" indent="yes"/>

 <xsl:template match="textfile[ @href ]">
  <xsl:copy-of select="unparsed-text( @href )"/>
 </xsl:template>

 <xsl:template match="@* | node()">
  <xsl:copy>
   <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
 </xsl:template>

</xsl:stylesheet>

For XSLT 1.0, you'd need a workaround involving an XML wrapper file referencing the textfile using an external entity, and the document() function.

like image 177
Lumi Avatar answered Dec 03 '25 05:12

Lumi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!