susi
susi

Reputation: 31

How to call XSLT from XSLT?

I'm looking for a possibility of calling a second XSLT from first XSLT.

My XML input looks like

<xml>
  <Subject name ="A1" type="a">
  <Subject name ="B2" type="b">
  <Subject name ="C1" type="c">
  <Subject name ="A2" type="a">
  <Subject name ="B1" type="b">
  <Subject name ="C2" type="c">
  <Subject name ="A3" type="a">
</xml>

What I want to do is something like

<xsl>
 if type = "a" call "XSL_A" with above XML-Input
 if type = "b" call "XSL_B" with above XML-Input
 if type = "c" call "XSL_C" with above XML-Input

 Do-Something with above XML-Input
<xsl>

Every "sub-xslt" shall take the complete input and do something with it, including creating a special named file.

As searching the web for a solution or a hint hasn't been successful. Is this possible to do? Or even sensible?

Upvotes: 3

Views: 3031

Answers (2)

kjhughes
kjhughes

Reputation: 111491

Or even sensible?

No, it is not sensible to think of calling XSLT procedurally, but that you're asking the question is a good sign that you're recognizing that there's probably a better way...

Pattern matching

Do not think procedurally in terms of "calling" other XSLT. Think instead declaratively in terms of pattern matching the input.

For

<Subject name ="A1" type="a"/>

instead thinking

  • if type = "a" call "XSL_A" with above XML-Input

think

  • When matching a Subject whose @type is "a", output something

or, in XSLT,

<xsl:template match="Subject[@type='a']>
    <something id="{@name}"/>
</xsl>

so that

<Subject name ="A1" type="a"/>

is translated to

<something id="a"/>

in the output.


XSLT file organization

Orthogonal to the above match-driven design approach, it is possible to organize and combine XSLT files. Use xs:include to bring in another stylesheet as a separate part of the one you're writing; use xs:import to bring in another stylesheet like or based on the one you're writing such that you'd like to override templates.

For more details on xs:include vs xs:import, see:

Modes

Finally, and orthogonal to both of the above dimensions, XSLT supports modes for controlling the applicability of a templates. For more information on modes, see Can one give me the example for “mode” of template in xsl?

Upvotes: 6

Martin Honnen
Martin Honnen

Reputation: 167401

If you really want to call an XSLT stylesheet dynamically then you need XSLT 3.0 with the https://www.w3.org/TR/xpath-functions-31/#func-transform function. On the other hand what you have posted with e.g. if type = "a" call "XSL_A" with above XML-Input simply looks like a possible search for template based matching and additionally modes with e.g. <xsl:template match="Subject[@type = 'a']" mode="a">...</xsl:template> where you could then write modules for each mode and include/import them in the main stylesheet.

Upvotes: 1

Related Questions