Explain Codes LogoExplain Codes Logo

Using copy-of with document() to add SVGs to XHTML output

xslt
namespace-management
svg-embedding
xslt-performance
Nikita BarsukovbyNikita Barsukov·Mar 9, 2025
TLDR

To embed SVGs directly into XHTML using XSLT, combine document() function to fetch the SVG XML and xsl:copy-of to insert it:

<xsl:copy-of select="document('your-svg.svg')/svg" />

Here, document('your-svg.svg') loads the SVG, and the /svg ensures you are precisely duplicating the <svg> element itself into your XHTML. It's critical that 'your-svg.svg' is a valid XML SVG file.

Namespace management in XSLT

SVG content often includes elements with namespaces, like xlink:href. XSLT's namespace-alias directive preserves these namespaces during the embedding process:

<xsl:namespace-alias stylesheet-prefix="aliased" result-prefix="xlink" />

In the XSLT copy operations, reference the declared prefix when handling namespaced attributes. This prevents accidental namespace transformations:

<xsl:copy-of select="document('your-svg.svg')/svg/*[namespace-uri() = 'aliased']" /> <!-- Here, aliens (namespace-uri) check for the validity of our passports (aliased prefix). If all is okay, they let us in. -->

Advanced scenarios & potential pitfalls

Cross-origin restrictions

Ensure cross-origin restrictions aren't blocking your SVG sources. The XSLT processor needs access.

Dynamic inclusion of SVGs

SVG files determined at runtime can be handled by dynamically constructing the URI:

<xsl:variable name="svgFile" select="'dynamic-svg.svg'" /> <xsl:copy-of select="document($svgFile)/svg" /> <!-- It's like calling your friend and saying, "Hey, draw this SVG?", and they're like, "Sure, what's the name?".-->

Preserving embedded CSS styles

Embedded CSS within SVGs can be preserved during the inclusion process:

<xsl:apply-templates select="document('styled-svg.svg')/svg/style" /> <!-- We're not just copying plain Jane SVGs, we're including their radiant personalities (styles) too. -->

Performance optimizations

SVG document caching

Avoid repetitive fetching and parsing of SVG files. Implement a caching mechanism to save computational resources.

SVG pre-processing

Make adjustments to SVG files before the XSLT process. Tools like Inkscape can streamline your task.