O'Reilly logo

XML Hacks by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required