Tankman六四
Tankman六四

Reputation: 1778

Embedding XSLT in the XML file?

Let's suppose we have:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="class.xsl"?>
<class>
    <student>Jack</student>
    <student>Harry</student>
    <student>Rebecca</student>
    <teacher>Mr. Bean</teacher>
</class>

This file would render nicely in a browser with a proper class.xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html><body>
  <ol>
    <xsl:for-each select="class/student">
      <li><xsl:value-of select="."/></li>
    </xsl:for-each>
  </ol>
  </body></html>
</xsl:template>

</xsl:stylesheet>

Is there a way to include the content of class.xsl in the same XML file, so that the file class.xsl does not exist?

I know this is possible with a CSS stylesheet, normally referred by <link>, can also be nested in.


Edit: I experimented with referencing the same XML file as the stylesheet, however, XSLT's <stylesheet> does not function if not used as the root element.

Is it possible to allow class.xsl to source some XSLT segment defined in the XML file and use it as XSLT? This would allow a generic XSLT file to be defined to load XSLT rules from each individual XML file.

Upvotes: 1

Views: 1379

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

In principle you can do it like this:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="#ssid"?>
<xx>
  <xsl:stylesheet version="1.0" id="ssid" xml:id="ssid"
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
   <html><body>
    <ol>
    <xsl:for-each select="//class/student">
      <li><xsl:value-of select="."/></li>
    </xsl:for-each>
    </ol>
   </body></html>
  </xsl:template>

 </xsl:stylesheet>
 <class>
    <student>Jack</student>
    <student>Harry</student>
    <student>Rebecca</student>
    <teacher>Mr. Bean</teacher>
 </class>
</xx>

I don't know how well-supported this is in browsers. According to comments on this answer, Chrome needs the xml:id attribute while Firefox needs the id attribute to recognize the fragment identifier #ssid.

Upvotes: 2

Related Questions