Various Tricks for XSLT


Table of Contents

1. Introduction
2. XSLT2TeX
3. MML Trick
4. Validating
5. Conclusion

1. Introduction

The idea is fairly simple I would say. xsltproc is available on majority of the popular platforms.

2. Use XSLT to convert epub books to TeX

A common issue is that XHTML used in epub is with a namespace. So that namespace should be specified in stylesheet header. Then for example xhtml:html can be referenced.

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

This snippet handles ruby.

<xsl:template match="xhtml:ruby">
  <xsl:variable name="kanji">
    <xsl:for-each select="text()">
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:variable>
  <xsl:text>\ruby[</xsl:text>
  <xsl:choose>
    <xsl:when test="string-length($kanji) = 1">
      <xsl:text>m</xsl:text>
    </xsl:when>
      <xsl:when test="count(xhtml:rt) = 1">
        <xsl:text>g</xsl:text>
      </xsl:when>
      <xsl:otherwise><xsl:text>j</xsl:text></xsl:otherwise>
  </xsl:choose>
  <xsl:text>]{</xsl:text><xsl:value-of select="$kanji"/>
  <xsl:text>}{</xsl:text>
  <xsl:for-each select="xhtml:rt">
    <xsl:value-of select="." />
    <xsl:if test="position() != last()"><xsl:text>|</xsl:text></xsl:if>
  </xsl:for-each>
  <xsl:text>}</xsl:text>
</xsl:template>

For example, <ruby>霊<rt>れい</rt>前<rt>ぜん</rt></ruby> can be converted to \ruby[j]{霊前}{れい|ぜん}.

3. Conditional enabling MathJax

It is possible to only embed MathJax script when there are MathML nodes in the document. Don't forget to declare xmlns:mml="http://www.w3.org/1998/Math/MathML".

<xsl:template name="user.head.content">
  <xsl:if test="///mml:math">
    <xsl:text disable-output-escaping="yes"><![CDATA[
<script>MathJax = {options: {enableMenu: false}}</script>
<script type="text/javascript" id="MathJax-script" async
        src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
]]></xsl:text>
  </xsl:if>
</xsl:template>

4. Validating

If you only have xmllint:

$ xmllint --noout --dtdvalid docbook-5.0.1/dtd/docbook.dtd doc.xml

5. Conclusion

Well, have fun with that!