Including an XML file in an XML/XSL file

I. Here is how any XML document or fragment can be embedded in an XSLT stylesheet and used during the transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <my:menu>
   <menu>
     <choice>A</choice>
     <choice>B</choice>
     <choice>C</choice>
   </menu>
 </my:menu>

 <xsl:template match="https://stackoverflow.com/">
  <xsl:copy-of select="document('')/*/my:menu/*"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used in this example), the wanted result (just copying the XML) is produced:

<menu xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
   <choice>A</choice>
   <choice>B</choice>
   <choice>C</choice>
</menu>

Remember: Any XML can be embedded into an XSLT stylesheet, provided it is wrapped into a namespaced element (the namespace not the XSLT namespace) and this wrapping element is at the global level (a child of the <xsl:stylesheet> (top) element).

II. Accessing the XML menu file that resides in a separate XML file:

To do this we have to change only slightly the previous example:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>


 <xsl:template match="https://stackoverflow.com/">
  <xsl:copy-of select="document('menu.XML')/*"/>
 </xsl:template>
</xsl:stylesheet>

If the menu XML file is in the 'menu.XML' file (in the same directory as the XSLT stylesheet file, then this transformation produces exactly the same result as the previous:

<menu>
   <choice>A</choice>
   <choice>B</choice>
   <choice>C</choice>
</menu>

Do note: In both cases we are using the standard XSLT function document()

Typically, one defines a global-level variable, whose value is the result of calling the document() function. Then this variable and its contents is accessed via XPath expressions during the transformation.

Leave a Comment