Hack 22 Convert an HTML Document to XHTML with HTML Tidy

figs/beginner.gif figs/hack22.gif

HTML Tidy was initially developed as a tool to clean up HTML, but it is an XML tool, too. This hack shows you how to use HTML Tidy to make your HTML into XHTML.

HTML Tidy was initially developed at the W3C by Dave Raggett (http://www.w3.org/People/Raggett/#tidy). Essentially, it's an open source HTML parser with the stated purpose of cleaning up and pretty-printing HTML, XHTML, and even XML. It is now hosted on Sourceforge (http://tidy.sourceforge.net). You can download versions of Tidy for a variety of platforms there.

Example 2-10 shows an HTML document, goodold.html, which we will run through HTML Tidy.

Example 2-10. goodold.html


<BODY style="font-family:sans-serif">


<TABLE style="font-size:14pt" cellpadding="10">




















Assuming that Tidy is properly installed, you can issue the following command to convert goodold.html to the XHTML document goodnew.html using the -asxhtml switch:

tidy -indent -o goodnew.html -asxhtml goodold.html

The -indent switch indents the output, and the -o switch names the output file. Tidy will issue warnings if necessary, and provide tips that encourage accessibility. The new file goodnew.html looks like Example 2-11.

Example 2-11. goodnew.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


<html xmlns="http://www.w3.org/1999/xhtml">


  <meta name="generator" content=

  "HTML Tidy for Windows (vers 1st January 2004), see www.w3.org" />





<body style="font-family:sans-serif">



  <table style="font-size:14pt" cellpadding="10">































What was once HTML is now well-formed, indented XHTML 1.0, an XML-ized version of HTML [Hack #61] . A document type declaration was added that references the strict XHTML 1.0 DTD, as well as a namespace declaration (http://www.w3.org/1999/xhtml), and all of the tag names were changed to lowercase. Other than a meta tag in the head section, the rest of the document remains similar to the original HTML.

There's a lot more possible with Tidy; for example, it gives you considerable control over character encodings with switches like -ascii, -utf8, and -utf16; allows you to replace the deprecated elements FONT, NOBR, and CENTER with CSS equivalents using the -clean or -c switch; lets you accept XML as input with -xml; and even converts XHTML back to HTML (-ashtml).