Search code examples
xsltdocumentfseek

XML XSLT Result-Document fseek


Using XSLT transformation I want to convert an XML file, that in turn represents various chunks of another file, into a HTML file with a link to the file that was represented.

Input XML File:

<File>
  <Name>foo.jpg<Name>
  <Chunk>
      <Offset>200</Offset>
      <Length>100</Length>
      <Data>
          <![CDATA[data bytes, encoded in base64, can be greater than length 100 too, but first 100 decoded bytes are valid.]]>
      </Data>
  </Chunk>
  <Chunk>
  ...
</File>

The output should be a html file that has a valid link to foo.jpg, i.e., there is another implicit output file called "foo.jpg" with data from the cdata sections in the chunks, at their specified offsets.

<html>
   <body>
      <a href="http://example.com/images/foo.jpg">file</a>
   </body>
</html>

Related question


Solution

  • This XSLT 2.0 transformation:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:template match="/*">
    
      <xsl:document>
            <html>
               <body>
                  <a href="http://example.com/images/{Name}">file</a>
               </body>
            </html>
      </xsl:document>
    
      <xsl:result-document href="file:///c:/temp/delete/{Name}" method="text">
        <xsl:apply-templates select="Chunk">
         <xsl:sort select="Offset" data-type="number"/>
        </xsl:apply-templates>
      </xsl:result-document>
     </xsl:template>
    
     <xsl:template match="Chunk">
      <xsl:value-of select="substring(Data, 1, Length)"/>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on this XML document (having two chunks):

    <File>
      <Name>foo.jpg</Name>
      <Chunk>
          <Offset>200</Offset>
          <Length>100</Length>
          <Data>A01234567891234567890234567890134567890124567890123567890123467890123457890123456890123456790123456780123456789</Data>
      </Chunk>
      <Chunk>
          <Offset>1</Offset>
          <Length>200</Length>
          <Data>Z0123456789123456789023456789013456789012456789012356789012346789012345789012345689012345679012345678012345678901234567891234567890234567890134567890124567890123567890123467890123457890123456890123456790123456780123456789</Data>
      </Chunk>
    </File>
    

    produces the wanted, correct result:

    <html>
       <body><a href="http://example.com/images/foo.jpg">file</a></body>
    </html>
    

    and the created file: c:\temp\delete\foo.jpg has the correct, wanted contents:

    Z0123456789123456789023456789013456789012456789012356789012346789012345789012345689012345679012345678012345678901234567891234567890234567890134567890124567890123567890123467890123457890123456890123456A012345678912345678902345678901345678901245678901235678901234678901234578901234568901234567901234567