Docbook - Change the background color of the row in a table according to the value of the <entry>

By xngo on February 22, 2019

<?xml version="1.0" encoding="UTF-8"?>
<!--
Description: 
  Change the background color of the row in a table according to the value of the <entry>.
  In this case, it will set the background color of the row to red if the value of the last column of the row is No(i.e. <entry>No</entry>).
Note: This is not a customization. It is simply an XSL stylesheet that needs to be applied on your docbook's xml file.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
 
  <!-- Copy everything -->
  <!-- ############# -->
  <xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
 
  <!--
    The core logic start here.
    -Catch all <row>.
    -Check whether the last <entry> is equal to 'No'.
      If it does, reconstruct the <row> element and at the same time, add the processing instruction to set the background color to red.
      Otherwise, reconstruct the <row> element.
  -->
  <xsl:template match="row">
    <xsl:choose>
      <!-- Check whether the last <entry> contains 'No' -->
      <xsl:when test="entry[last() and text()='No']">
        <xsl:element name="row">
          <xsl:apply-templates select="@*|node()"/><!-- Copy everything under <row>, preserve data -->
          <!-- Add the processing instruction to set the background color to red. -->
          <xsl:processing-instruction name="dbhtml">bgcolor="#FF0000"</xsl:processing-instruction>
          <xsl:processing-instruction name="dbfo">bgcolor="#FF0000"</xsl:processing-instruction>
        </xsl:element>
      </xsl:when>
 
      <xsl:otherwise>
        <xsl:element name="row">
          <xsl:apply-templates select="@*|node()"/><!-- Copy everything under <row>, preserve data -->
        </xsl:element>
      </xsl:otherwise>
 
    </xsl:choose>
  </xsl:template>
 
</xsl:stylesheet>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.