I intend to implement Martin Fowler's Two-Step View Pattern for rendering HTML in a web application I'm writing. The general idea is that rather than having the application output raw HTML, it outputs an custom intermediary XML which is then converted to HTML/CSS. This has a number of advantages including reduced code duplication and a more consistent output.
The approach suggested by Fowler for converting the XML to the final HTML is to use XSLT.
I've used XSLT before and I know the basics. However, I'm wondering what are the advantages of using XSLT. An alternative approach I'm considering looks like this:
Here is an example XML output of the first rendering step:
<grid>
<headingRow>
<cell>Product</cell>
<cell>Price</cell>
</headingRow>
<row>
<cell>A product</cell>
<cell type="price">$54.95</cell>
</row>
</grid>
And the desired final HTML output:
<table class="grid">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>A product</td>
<td>
<span class="currency_symbol">$</span>
<span class="decimal_number">54.95</span>
</td>
</tr>
</table>
The approach I'm considering would have one object for each tag.
class GridTag extends Tag {
...
public void render() {
System.out.println("<table class=\"grid\">");
foreach(Tag child: children) {
child.render();
}
System.out.println("</table>");
}
...
}
The objects would constructed into a tree by parsing the XML. The render() method would be call on the root node. I particularly like this approach because it allows me to do cool things. Particularly, if I have a cell tag as above of with the attribute type="price":
<cell type="price">$54.95</price>
It's associated Tag class could parse the contents of the tag to separate the currency symbol and the numerical value into separate HTML tags to allow the alignment of the currency symbol and the decimal point, as in the HTML output above.
<td>
<span class="currency_symbol">$</span>
<span class="decimal_number">54.95</span>
</td>
Questions:
Should I do this or should I use XSLT? What are the advantages of using XSLT that I might miss out on? If I should use XSLT, how would I go about parsing the contents of the price tag?