XSLT `xsl:import` Element: Creating Modular and Reusable Stylesheets
Learn how to create modular and reusable XSLT stylesheets using the `xsl:import` element. This tutorial explains how to import stylesheets, manage template precedence, and build more maintainable and efficient XSLT transformation processes by reusing code across multiple stylesheets.
Using the XSLT `xsl:import` Element
The XSLT `xsl:import` element is used to import the contents of one XSLT stylesheet into another. This is useful for reusing stylesheet code and creating modular stylesheets. The importing stylesheet has higher precedence over the imported stylesheet; in other words, if there are any conflicting rules, the ones defined in the importing stylesheet will take precedence.
`xsl:import` Element Syntax and Attributes
<xsl:import href="stylesheet_to_import.xsl"/>
The `href` attribute specifies the path to the XSLT stylesheet to be imported. The imported stylesheet's templates are then available within the importing stylesheet. Note that templates in the importing stylesheet override those in the imported stylesheet if they have matching match patterns.
Example: Importing an XSLT Stylesheet
(Note: This example requires creating `employee.xml`, `employee.xsl`, and `employee_import.xsl` files. Screenshots from the original text are not included here. Please refer to the original document for visual verification of the example and XSLT output. The descriptions below aim to convey the information present in those screenshots.)
This example demonstrates importing a stylesheet (`employee.xsl`) into another stylesheet (`employee_import.xsl`). The `employee.xml` file is the XML data source.
`employee.xml` (Example XML Data)
<employees>
<employee>
<firstName>Aryan</firstName>
<lastName>Gupta</lastName>
<nickName>Raju</nickName>
<salary>30000</salary>
</employee>
<employee>
<firstName>Sara</firstName>
<lastName>Khan</lastName>
<nickName>Zoya</nickName>
<salary>25000</salary>
</employee>
<!-- ... more employee elements ... -->
</employees>
`employee.xsl` (Imported Stylesheet)
(The original content includes the content of the `employee.xsl` file. Since we cannot display the file here, please refer to the original document for the file content.)
`employee_import.xsl` (Importing Stylesheet)
(The original content includes the content of the `employee_import.xsl` file. Since we cannot display the file here, please refer to the original document for the file content.)
(The original content includes a screenshot showing the output. Since we cannot display images, please refer to the original document for the visual representation of the output. The description below aims to convey the information in the screenshot.)
The output shows the transformed XML data in a tabular format. The `employee_import.xsl` stylesheet reuses the templates from `employee.xsl`.