Convert an HTML Document to XHTML with HTML Tidy

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

<HTML>
<HEAD><TITLE>Time</TITLE></HEAD>
<BODY style="font-family:sans-serif">
<H1>Time</H1>
<TABLE style="font-size:14pt" cellpadding="10">
<TR>
 <TH>Timezone</TH>
 <TH>Hour</TH>
 <TH>Minute</TH>
 <TH>Second</TH>
 <TH>Meridiem</TH>
 <TH>Atomic</TH>
</TR>
<TR>
 <TD>PST</TD>
 <TD>11</TD>
 <TD>59</TD>
 <TD>59</TD>
 <TD>p.m.</TD>
 <TD>true</TD>
</TR>
</TABLE>
</BODY>
</HTML>

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 ...

Get XML Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.