Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: How do I trigger a template when there is no input file?

Tags:

xslt

I'm creating a template which produces output based on a single string, passed via parameter, and does not use an input XML document. xsltproc seems to happily run with a single parameter specifying the stylesheet, but I don't see a way to trigger a template without an input file (no parameter to xsltproc to run a named template, for example).

I'd like to be able to run:

xsltproc --stringparam bar baz foo.xsl

But I'm currently having to run, with the "main" template matching "/":

echo '<xml/>' | xsltproc --stringparam bar baz foo.xsl -

How can I get this to work? I'm sure I've seen other templates in the past which were meant to be run without an input document, but I don't remember how they worked or where to find them again. :-)

like image 844
Ben Blank Avatar asked Dec 22 '22 10:12

Ben Blank


2 Answers

Actually, this has been done quite often.

In XSLT 2.0 it is defined in the Spec. that providing an initial context node is optional. If no initial context node is provided (no source XML document), then it is important to provide the name of a named template which is to be executed as the entry point to the transformation.

In XSLT 1.0 one can provide to the transformation its own primary stylesheet module (file) as the source XML document, and of course, the transformation can completely ignore this source XML document. This technique has long ago been demonstrated and used by Jeni Tennison.

For example:

<?xml-stylesheet type="text/xsl" href="example.xml"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
      <p>Hello, world!</p>
    </xsl:template>
</xsl:stylesheet>

When the above code is saved in a file named "example.xml" and then the folder contents is displayed with Windows Explorer, double-clicking on the file "example.xml" will open IE and produce:

Hello, world!

like image 171
Dimitre Novatchev Avatar answered Jan 05 '23 23:01

Dimitre Novatchev


In general, you cannot do this with XSLT - specification requires there to be an input document, and for the processing to start with applying any available templates to its root node. Some XSLT processors might give a way to do what you want (e.g. execute a named template) as an extension, but I don't know any such, and it doesn't seem that xsltproc is one of them, judging from its man page.

In fact, this sounds pretty dubious in general, as the purpose of using XSLT to produce some output from a plain string input is unclear - it's not the kind of task it's generally good at.

like image 20
Pavel Minaev Avatar answered Jan 05 '23 22:01

Pavel Minaev