Explain Codes LogoExplain Codes Logo

Set HTML5 doctype with XSLT

html
doctype
xslt
html5
Anton ShumikhinbyAnton Shumikhin·Dec 21, 2024
TLDR

Utilize the <xsl:output> element in XSLT and leave doctype-public and doctype-system attributes empty to set the HTML5 doctype:

<xsl:output method="html" doctype-public="" doctype-system=""/>

This in effect outputs:

<!DOCTYPE html>

With XSLT 1.0, you can generate the HTML5 doctype using:

<xsl:output method="html" doctype-system="about:legacy-compat"/>

For XSLT 2.0+, utilize:

<xsl:output method="html" doctype-public="" doctype-system="about:legacy-compat"/>

Don't forget to check your processor's support for disable-output-escaping, as support across XSLT engines is not universally uniform.

Write the doctype directly if needed

Using disable-output-escaping

If your XSLT engine doesn't support doctype-system or doctype-public, write the doctype directly by disabling output escaping:

<xsl:text disable-output-escaping='yes'>&lt;!DOCTYPE html&gt;</xsl:text>

Fair warning, this option isn't universally supported, so check your processor's support again. Looking at you, Internet Explorer!

Switch to Saxon for HTML5 compatibility

An XSLT processor like Saxon 9.4 or newer is handy, facilitating better HTML5 output:

<xsl:output method="html" version="5.0"/>

This is a very Saxony piece of code, don't you think? 😉

Evaluating the use of legacy-compat

"About:legacy-compat" may not be needed always

about:legacy-compat was essentially introduced to help browsers handle the good old quirks mode. However, it's akin to using a sledgehammer to crack a nut. You most likely won't need it, but hey, it's there if you do!

Optimizing doctype for different XSLT processors

Each processor has its own quirks

Consult the documentation of your chosen XSLT processor, as different ones handle the output differently. Saxon users, you're in luck, the Saxon documentation is quite comprehensive!

A clean HTML5 doctype results in seamless compatibility

Strive for cleanliness with your HTML5 doctype. No extra attributes or values, please. This ensures your document remains functional across various platforms.

Validating and debugging your doctype

Check your results with a validator

Run the resulting document by a validator to ensure your doctype and the HTML is properly formed. It's like your friendly neighborhood Spiderman — always ready to catch bugs!

No output as expected? Let's play detective!

If things don't look right, take advantage of the debugging tools in your XSLT processor. A fun trick is to use temporary markers in your XSLT to isolate the mischievous line of code. Who needs Sherlock Holmes?

Stay updated, stay relevant

Keep an eye on updates from W3C specifications for staying ahead of the curve. As Spiderman says, "With great power comes great responsibility."