XML technologies / Schematron / Schematron cookbook / Web technologies

(Excerpt from "Schematron - Effiziente Business Rules für XML-Dokumente", chapter 8)

HTML was designed to let a broad audience create pages simply and with tolerance for errors. Browsers therefore interpret and display almost any code rather than reject incorrect content or syntax. XML’s introduction turned HTML into XHTML, subject to XML’s well-formedness rules. Beyond the standard’s validatable constraints, XHTML authors should follow additional design guidelines, also published by W3C. Some help browsers and search engines process and index pages optimally. Others concern layout, readability and access for groups such as visually impaired users.

Many recommendations cannot be checked by W3C’s DTDs. Some cannot technically be checked with DTD or XML Schema; others could extend the XHTML DTD, but would further complicate authoring.

We now present some rules and demonstrate checking them with Schematron.

The lang attribute

XHTML’s universal attribute lang specifies content language using a language code from RFC 17665. It can appear on almost any element, for example for a foreign-language quotation. Language attributes matter for accessibility and screen readers: incorrect language leads to pronunciation that may make text hard to understand.

Since XHTML is XML, language can also use universal XML attribute xml:lang . For screen readers, W3C recommends both lang and xml:lang attributes with identical values. This can cause mistakes or conflicts, as here:

 

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Zitate Niccolò Machiavelli</title>
  </head>
  <body>
    <h1>Zitate <span lang="it">Niccolò Machiavelli</span></h1>
    <p>Man kann einen Krieg beginnen, aber niemals beenden, wenn man will.</p>
    <p lang="it" xml:lang="de">Può la disciplina nella guerra più che il furore.</p>
  </body>
</html>

This document is XHTML-conformant but has weaknesses in its lang attributes. Both lang and xml:lang are absent from element root. Elsewhere, values differ or attribute xml:lang is missing.

This schema checks those language-attribute inconsistencies:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
  <ns uri="http://www.w3.org/1999/xhtml" prefix="html"/>
  <pattern>
    <rule context="html:html">
      <assert test="@lang">Das Attribut "lang" fehlt.</assert>
      <assert test="@xml:lang">Das Attribut "xml:lang" fehlt.</assert>
    </rule>
  </pattern>
  <pattern>
    <rule context="*[@xml:lang and @lang]">
      <assert test="@lang = @xml:lang">Die Werte der Attribute "lang" und "xml:lang" sollten identisch sein.</assert>
    </rule>
    <rule context="*[@lang]">
      <assert test="@xml:lang">Das Attribut "xml:lang" fehlt.</assert>
    </rule>
    <rule context="*[@xml:lang]">
      <assert test="@lang">Das Attribut "lang" fehlt.</assert>
    </rule>
  </pattern>
</schema>

Assign each document a central language through element <html>. Different languages can then be specified locally. Always use both lang and xml:lang with identical values. ISO 3166 and 639 describe registered country codes that can be used as values.

Headings

XHTML headings use elements <h1> through <h6>. They must provide logical structure, not just visual formatting. Thus heading <h1> should be followed immediately by <h1> or <h2> , not <h3>.

You may wonder what this is all for.
Headings help visually impaired users navigate between chapters. This requires correct use rather than, for example, marking an image caption with <h6> . Extra rules beyond validity also help when content is reused years later in another context or XML grammar. Incorrect heading hierarchies can seriously complicate transformation and force manual editing.

Here is an incorrectly structured XHTML file.

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Böse Hierarchie</title>
  </head>
  <body>
    <h1>1. Einführung</h1>
    <h4>1.1 Vorwort</h4>
  </body>
</html>

Schematron helps here too. These rules illustrate the check.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xslt2">
  <ns prefix="html" uri="http://www.w3.org/1999/xhtml"/>
  <pattern>
    <!--Die folgende Regel prüft, ob die erste Überschrift des Dokuments als h1 getaggt wurde.-->
    <rule context="html:body">
      <let name="firstDescendantHeading" value="descendant::node()[name()=('h1','h2','h3','h4','h5','h6')][1]"/>
      <assert test="$firstDescendantHeading/self::html:h1">Die erste Überschrift in einem Dokument muss h1 sein.</assert>
    </rule>
    <!--Die Grundüberlegung: h1- und h2-Elemente können niemals eine Überschriftenebene übersprungen haben. Erst ab der dritten Hierarchiestufe kann dieser Fall eintreten. Die erste Regel überprüft dementsprechend alle h3-Elemente darauf, ob die nächst vorangegangene Überschrift eine h1 ist (denn alle anderen Überschrift-Typen können richtig sein).-->
    <rule context="html:h3">
      <let name="firstPrecedingHeading" value="preceding::node()[name()=('h1','h2','h3','h4','h5','h6')][1]"/>
      <report test="$firstPrecedingHeading/self::html:h1" diagnostics="HierarchyCrashLevel1">Eine Überschriftenebene wurde ausgelassen: Eine h3 darf nicht auf eine <value-of select="$firstPrecedingHeading/name()"/> folgen.</report>
    </rule>
    <!-- Die nächste Regel geht analog zur vorherigen vor. Sie überprüft alle h4-Elemente auf zwei Bedingungen. Erstens: Die nächst vorangegangene Überschrift darf keine h1 sein. Zweitens: Die nächst vorangegangene Überschrift darf auch keine h2 sein. Mit Hilfe der Diagnostics bekommt der Benutzer eine konkrete Handlungsanweisung, um das Problem zu lösen. Ihm wird in diesem Fall vorgeschlagen, das fehlerhafte Tag zu ändern, sodass die Hierarchie wieder stimmt.-->
    <rule context="html:h4">
      <let name="firstPrecedingHeading" value="preceding::node()[name()=('h1','h2','h3','h4','h5','h6')][1]"/>
      <report test="$firstPrecedingHeading/self::html:h1" diagnostics="HierarchyCrashLevel1">Zwei Überschriftenebenen wurden ausgelassen: Eine h4 darf nicht auf eine <value-of select="$firstPrecedingHeading/name()"/> folgen.</report>
      <report test="$firstPrecedingHeading/self::html:h2" diagnostics= "HierarchyCrashLevel2">Eine Überschriftenebene wurde ausgelassen: Eine h4 darf nicht auf eine <value-of select="$firstPrecedingHeading/name()"/> folgen.</report>
    </rule>
  </pattern>
    <diagnostics>
      <diagnostic id="HierarchyCrashLevel1">Ändern Sie das Element für die Überschrift '<value-of select="."/>' in h2, um einen Unterabschnitt von '<value-of select="$firstPrecedingHeading"/>' einzuleiten!</diagnostic>
      <diagnostic id="HierarchyCrashLevel2">Ändern Sie das Element für die Überschrift '<value-of select= "."/>' in h3, um einen Unterabschnitt von '<value-of select="$firstPrecedingHeading"/>' einzuleiten!</diagnostic>
    </diagnostics>
</schema>

The first rule checks that the initial heading is tagged <h1>. If it holds, <h1> and <h2> elements cannot have skipped a level. Skipping is possible only from the third level onward. Another rule therefore checks all <h3> elements for a preceding heading of type <h1>, since all other heading types may be correct.

Here we use XPath 2.0 functions for the first time. Attribute queryBinding is therefore required, with value xstl2 instructing the parser to evaluate functions from XPath 2.0. For further values of queryBinding, see element <schema> in the Schematron reference.

The page title

Element <title> defines the document title displayed in browser title bars and search results. Choose a meaningful, concise title. A guideline is about 60–70 characters; longer titles may be truncated in results, as illustrated.

Search-engine result

Figure: search-engine result

The result’s full title is: „Ihre Spezialisten für XML XSL-FO - WordML - XSL - XSLT - XML aus einer Hand | Data2Type“, but exceeding 70 characters unfortunately leaves only the last word, “Data2Type”, visible.

This example has two possible problems that Schematron can check.

<html xmlns="http://www.w3.org/1999/xhtml" lang="de" xml:lang="de">
  <head>
    <title>Ungeeignetes title-Element mit viel zu vielen Zeichen, es handelt sich hierbei um über 70 Zeichen <!-- verbotener Kommentar --></title>
  </head>
  <body> <!-- Content --> </body>
</html>

Besides a suitable character count, a title element should contain no comments. This pattern checks both:

<pattern>
  <rule context="html:title">
    <report test="comment()"> In title-Elementen sollen keine Kommentare vorkommen.</report>
    <report test="self::node()[string-length() &gt; 70]">Der Text im title-Element ist zu lang.</report>
    <report test="normalize-space(text()) = ''">Es fehlt der Titel-Text...</report>
  </rule>
</pattern>

XHTML tables I

XHTML tables, widely used in online and print publishing, have many potential problems that cannot be checked with an XML schema or DTD.

Column, cell and overall table widths may conflict. A table’s width attribute might be 100 percent while the total of width attributes on <col> elements is not exactly 100 percent, making correct browser rendering uncertain.

Schematron has limits here too: the number, complexity and interaction of errors hinder a generic solution. Mixing percentages, pixels and perhaps points makes compliance depend on available width; so many interacting rules make meaningful checking hardly practical.

This XHTML table fragment illustrates the problem.

…
<table>
  <col valign="top" width="19%"/>
  <col valign="top" width="82%"/>
  <thead>
    <tr>
      <th>XSLT</th>
      <th>Schematron</th>
    </tr>
  </thead>
  <tbody>
    <tr>…</tr>
…

The total column width exceeds 100 percent!

This pattern checks whether col-element widths total more than 100 percent:

<pattern>
  <rule context="html:table">
    <let name="colWidthSummarized" value="number(sum(for $colWidth in html:col/@width return number(substring-before($colWidth,'%'))))"/>
    <assert test="$colWidthSummarized &lt;= 100">Die Summe der Attributangaben @width in allen Spaltendefinitionen col ist mit <value-of select="$colWidthSummarized"/>% größer als 100%!</assert>
  </rule>
</pattern>

XHTML tables II

Checking spanning cells is complex and common in web and print tables. Correct XHTML rendering requires at least:

  • Every row must contain the same number of cells.

  • Spanning cells must not overlap.

This example contains errors ordinary schema languages cannot check:

<table border="1">
  <tbody>
    <tr>
      <td rowspan="2">A1</td>
      <td>B1</td>
      <td>C1</td>
      <td rowspan="3">D1</td>
      <td>E1</td>
    </tr>
    <tr>
      <td>B2</td>
      <td>C2</td>
      <td>E2</td>
      <td>F2</td>
    </tr>
    <tr>
      <td>A3</td>
      <td>B3</td>
      <td colspan="2">C3</td>
      <td>E3</td>
    </tr>
  </tbody>
</table>

XHTML table with spanning cells

Figure: XHTML table with spanning cells

Row two has one more cell than the others, although it contains fewer <td> elements than row one. C3 and D1 overlap: C3 spans columns three and four, while D1 occupies column four across rows one to three.

Schematron alone reaches its limits. Custom recursive XSLT functions must be incorporated into the schema.

Functions created in XSLT 2.0 using element <xsl:function> can be incorporated at the schema’s top level. Within <xsl:function>, all XSLT elements are allowed. Both <xsl:function> and every other XSLT element must belong to XSLT’s namespace.

Declare the XSLT namespace on <schema>, but the function namespace and its prefix with Schematron element <ns>. The function is then available in every XPath expression in the schema.

<schema xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://purl.oclc.org/dsdl/schematron" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" queryBinding="xslt2">
  <ns prefix="d2t" uri="http://www.data2type.de/html"/>
  <ns prefix="html" uri="http://www.w3.org/1999/xhtml"/>
  <xsl:function name="d2t:getColAndRows">
    <xsl:param name="preCells"/>
    <xsl:param name="cells"/>
    <xsl:variable name="cellsWithRows">
      <xsl:choose>
        <!-- wird zur Initialisierung beim ersten Aufruf der Funktion verwendet: -->
        <xsl:when test="$cells[not(@d2t:rowNumber)] | $cells[not(@colspan|@rowspan)]">
          <xsl:for-each select="$cells">
            <xsl:copy>
              <xsl:attribute name="d2t:rowNumber" select="count(../preceding-sibling::html:tr | ../parent::*[not(self::html:table)]/preceding-sibling::*/html:tr) + 1"/>
              <xsl:attribute name="colspan" select="'1'"/>
              <xsl:attribute name="rowspan" select="'1'"/>
              <xsl:attribute name="d2t:tableID" select="generate-id(./ancestor::html:table[1])"/>
              <xsl:attribute name="d2t:cellID" select="generate-id()"/>
              <xsl:copy-of select="@*"/>
              <xsl:apply-templates/>
            </xsl:copy>
          </xsl:for-each>
        </xsl:when>
        <!-- für alle rekursiven Aufrufe: -->
        <xsl:otherwise>
          <xsl:copy-of select="$cells"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    <xsl:variable name="cells" select="$cellsWithRows//html:td"/>
    <xsl:choose>
      <xsl:when test="count($cells)=0">
        <xsl:copy-of select="$preCells"/>
        <xsl:copy-of select="$cells"/>
      </xsl:when>
      <!-- falls nur die erste Zelle der Tabelle übergeben wird: -->
      <xsl:when test="count($cells)=1 and count($preCells)=0">
        <html:td>
          <xsl:attribute name="d2t:colNumber">1</xsl:attribute>
          <xsl:copy-of select="$cells/@*"/>
          <xsl:copy-of select="$cells/node()"/>
        </html:td>
      </xsl:when>
      <xsl:otherwise>
        <!-- rekursive Aufrufe jeweils mit der ersten und zweiten Hälfte der <td>-Elemente -->
        <xsl:variable name="half" select="count($cells) div 2"/>
        <xsl:variable name="firstHalf" select="d2t:getColAndRows($preCells, $cells[position() &lt; $half])"/>
        <xsl:variable name="secondHalf" select="d2t:getColAndRows(($firstHalf), $cells  [position() &gt;= $half][not(position()=last())])"/>
        <xsl:variable name="cell" select="$cells[last()]"/>
        <xsl:variable name="preCells" select="($secondHalf)"/>
        <xsl:variable name="preCell" select="$preCells[last()]"/>
        <!--  vorläufige Spaltennummer: -->
        <xsl:variable name="colOhneRowspan" select="if (($preCell/@d2t:rowNumber) &lt; ($cell/@d2t:rowNumber)) then (1) else (($preCell/@d2t:colNumber) + ($preCell/@colspan))"/>
        <!-- endgültige Spaltennummer: -->
        <xsl:variable name="colMitRowspan" select="d2t:getCol($colOhneRowspan, $cell/@d2t:rowNumber, $preCells[(@rowspan) &gt; 1])"/>
        <!-- Ausgabe der Zellen: -->
        <xsl:copy-of select="$preCells"/>
        <html:td>
          <xsl:attribute name="d2t:colNumber" select="$colMitRowspan"/>
          <xsl:copy-of select="$cell/@*"/>
          <xsl:copy-of select="$cell/node()"/>
        </html:td>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:function>
  <xsl:function name="d2t:getColAndRows">
    <xsl:param name="cells"/>
    <xsl:copy-of select="d2t:getColAndRows((),$cells)"/>
  </xsl:function>
  <xsl:function name="d2t:getCol">
    <xsl:param name="curCol"/>
    <xsl:param name="curRow" as="xs:integer"/>
    <xsl:param name="preCells"/>
    <xsl:choose>
      <!-- rekursiver Aufruf, falls eine zeilenüberspannende Zelle die Zeile $curRow in der Spalte $curCol überspannt -->
      <xsl:when test="$preCells [(@d2t:colNumber) &lt;= $curCol and $curCol &lt; @d2t:colNumber + @colspan][@d2t:rowNumber + @rowspan &gt; $curRow]">
        <xsl:value-of select="d2t:getCol($curCol + 1, $curRow, $preCells)"/>
      </xsl:when>
      <!-- Ausgabe der $curRow als endgültige Spaltennummer -->
      <xsl:otherwise>
        <xsl:value-of select="$curCol"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:function>
  <let name="cells" value="for $table in //html:table return d2t:getColAndRows($table//html:td)"/>
  <pattern>
    <rule context="html:td[(@colspan) &gt; 1]">
      <let name="tableID" value="generate-id(./ancestor::html:table[1])"/>
      <let name="cellID" value="generate-id()"/>
      <!-- alle Zellen dieser Tabelle:-->
      <let name="cells" value="$cells[@d2t:tableID=$tableID]"/>
      <let name="rowNumber" value="count(  ../preceding-sibling::html:tr | ../parent::*[not(self::html:table)]/preceding-sibling::*/html:tr)+1"/>
      <!-- akutelle Zelle mit ermittelter Spaltennummer:-->
      <let name="cell" value="$cells[@d2t:cellID=$cellID]"/>
      <!-- ermittelt alle Zellen, die in dieser Zeile stehen oder diese überspannen: -->
      <let name="row" value="$cells  [(@d2t:rowNumber) + (@rowspan) &gt; ($rowNumber)][(@d2t:rowNumber) &lt;= ($rowNumber)]"/>
      <!-- Spaltennummern, in denen sich Zellen überschneiden: -->
      <let name="cross" value="$row[(@d2t:colNumber) &lt; ($cell/@d2t:colNumber) + ($cell/@colspan)][(@d2t:colNumber) + (@colspan) &gt;= $cell/@d2t:colNumber + $cell/@colspan][not(@d2t:cellID=$cellID)]"/>
      <assert test="count($cross) = 0">Diese Zelle überschneidet sich mit der/n zeilenüberspannenden Zelle/n aus den Spalten <value-of select="for $x in $cross return if ($x = $cross[last()]) then ($x/@d2t:colNumber) else (concat($x/@d2t:colNumber, ','))"/>.</assert>
    </rule>
    <rule context="html:tr">
      <let name="tableID" value="generate-id(./ancestor::html:table[1])"/>
      <!-- alle Zellen dieser Tabelle:-->
      <let name="cells" value="$cells[@d2t:tableID=$tableID]"/>
      <!-- äußerste gefüllte Spalte: -->
      <let name="maxCol" value="xs:integer(max(for $cell in $cells return ($cell/@d2t:colNumber + $cell/@colspan - 1)))"/>
      <let name="rowNumber" value="count(preceding-sibling::html:tr | parent::*[not(self::html:table)]/preceding-sibling::*/html:tr)+1"/>
      <!-- gibt für jede mögliche Spalte die Zellen aus, die in dieser Spalte und in der aktuellen Zeile stehen: -->
      <let name="row" value="for $i in (1 to ($maxCol)) return ($cells[  (@d2t:colNumber) &lt;= $i and $i &lt; (@d2t:colNumber) + (@colspan)][(@d2t:rowNumber) + (@rowspan) &gt; ($rowNumber)][(@d2t:rowNumber) &lt;= ($rowNumber)])"/>
      <!-- verlan&gt;e Anzahl an Spalten: -->
      <let name="forcedColCount" value="if (ancestor::html:table[1]//html:col) then (count(ancestor::html:table[1]//html:col)) else ($maxCol)"/>
      <assert test="count($row) &gt;= $forcedColCount">Es fehlen Zellen. (Anzahl fehlender Zellen: <value-of select="$forcedColCount - count($row)"/> von <value-of select="$forcedColCount"/>)</assert>
      <report test="count($row) &gt; $forcedColCount">Es gibt zu viele Zellen. (Anzahl überflüssiger Zellen: <value-of select="count($row) - $forcedColCount"/>)</report>
    </rule>
  </pattern>
</schema>

The schema has three parts:

(1) function d2t:getColAndRows()

(2) function d2t:getCols()

(3) Schematron pattern

The d2t:getColAndRows() function

Pass all table <td> elements as parameters. The function returns a collection of <td> elements, each with attribute d2t:colNumber for the column number and d2t:rowNumber for the row number. Its task is to find each cell’s correct coordinates.

The schema contains two d2t:getColAndRows() functions. Recursive calls require two parameters. A one-parameter call invokes the two-parameter function, supplying an empty sequence first and all <td> elements second.

Using divide and conquer, the function recursively processes all <td> elements except the last. When only one <td> element—the table’s first—is passed, both attribute d2t:colNumber and d2t:rowNumber equal 1.

With more than one cell, the last cell’s column is computed from preceding <td> elements’ row and column numbers. Row numbers for all <td> elements are determined on the first call. This uses function d2t:getCols().

For speed and fewer recursive calls on large tables, split the <td> elements into halves ($firstHalf and $secondHalf) and recursively process both. The extra parameter $preCells is needed because column numbers for the second half of <td> elements can only be computed if the first half’s column numbers are supplied.

The d2t:getCols() function

Initially ignore row spans and calculate a provisional column number ($colOhneRowspan), correct if no row-spanning cell displaces it. Finding the actual column is the task of d2t:getCols(). Its parameters are provisional column, row number and all preceding cells.

Check whether a preceding cell spans the current row at the provisional column. If not, return that column. Otherwise recurse with the provisional column increased by one until no row span displaces the cell, then return the resulting column.

Schematron pattern

For further speed, top-level variable $cells stores, for each <table> element, the column numbers of its <td> elements. To associate them uniquely, the initial call to d2t:getColAndRows() uses generate-id() to assign each <td> element its corresponding <table> element’s ID in attribute d2t:tableID.

Two rules implement the actual checks: one tests whether horizontally spanning cells overlap vertically spanning cells; the other counts cells per row to find excess or missing cells.

   

 

 

 

back to top