All <xsl:import>
elements must appear as the first top-level elements in the importing style sheet. By contrast, <xsl:include>
elements can appear anywhere among other top-level elements in the including style sheet.
The main difference between <xsl:import>
and <xsl:include>
is that the template rules and other top-level elements embedded with <xsl:import>
are processed according to the explicit rules of import precedence. This enables you to control the ways in which conflicting or overlapping styles are applied, in a predictable fashion. Any template rules imported into a style sheet have a lower import precedence than those that physically reside in that style sheet. Template rules included in a style sheet have the same import precedence as those in the including style sheet.
Consider a style sheet, main.xsl. Suppose you want to logically incorporate the contents of another style sheet, sub_1.xsl, into main.xsl. Furthermore, you want to incorporate sub_2.xsl in sub_1.xsl. The main.xsl style sheet has a template rule for processing an <a>
element. The sub_1.xsl style sheet has a template rule for processing a <b>
element. The sub_2.xsl style sheet has template rules for both an <a>
element and a <b>
element.
Whether you use <xsl:include>
or <xsl:import>
, the general logical structure of the three style sheets might be represented as follows:
main.xsl
sub_1.xsl:
template rule for <b>
sub_2.xsl:
template rule for <a>
template rule for <b>
main.xsl's own template rule for <a>
If main.xsl includes both sub_1.xsl and sub_2.xsl, the <a>
and <b>
elements are processed according to the default rules for resolving conflicts. According to the XSLT standard, conflicting template rules are an error. Therefore, some XSLT processors might treat this situation as an error.
Alternatively, the standard allows the processor to accept the last such template rule in the style sheet, ignoring the others. Microsoft's XSLT processor (like most) follows this alternative processing route. Therefore:
<b>
in sub_2.xsl will override that in sub_1.xsl, because the one in sub_2.xsl appears later in main.xsl.<a>
in main.xsl itself will override that in sub_2.xsl, because the one in main.xsl appears later.Two rules determine the import precedence of a conflicting declaration:
According to these rules, if the connections among the three style sheets are all <xsl:import>
elements, the following statements are true:
<b>
which appears in sub_1.xsl will override that in sub_2.xsl, because sub_1.xsl imports sub_2.xsl, and therefore the declarations in sub_1.xsl have a higher import precedence. This is the opposite of what happens if you use <xsl:include>
in the same situation.<a>
which appears in main.xsl itself will override that in sub_2.xsl, because main.xsl imports sub_2.xsl. This result is identical to the result when using <xsl:include>
but for a different, explicit reason.