Server-side XML-to-HTML translation

How do you convert XML to HTML on the server side?

Q: I want to generate XML-based pages using the XSL on the server side so that the client gets plain HTML, rather than the XML plus an XSL page. What’s the best way to go about doing this?

A: Unfortunately, we can’t count on the client — not all browsers support XML-to-HTML conversion, and it will take quite some time before all users adopt browsers that will do the transformation. It’s true that we can sniff for the user’s browser type through a bit of code, and, if the browser supports XSL transformation, we could pass the work to the client. However, if/else browser identification remains a nonoptimal approach, since it’s difficult to maintain and places an unnecessary burden on the developer.

In the meantime, we have to figure out a way to do the conversion on the server. Two server-side approaches quickly come to mind: servlets and JSP. If you want to employ XSL conversion, you will need an XSL parser — and fortunately there are some excellent parsers available for free (see Resources).

Once you have a parser, you can easily incorporate the XML-to-HTML functionality directly into a servlet or a JavaServer Page. Whether you use servlets or JSPs is really up to you; the mechanics are largely the same. Simply feed the XML and XSL to the parser, then print out the HTML as your response.

If you’re new to servlets and JSPs, I suggest that you go and pick up Tomcat, a reference implementation of the servlet and JSP standards. It’s an excellent starting point and contains many examples (see Resources).

Depending on the complexity of the XML files you will convert, you can skip the XSL transformation entirely. Have a look at Alex Chaffee’s “Using XML and JSP Together,” (JavaWorld, March 31, 2000), which discusses XML-to-HTML conversion using JSPs. Alex’s article is a good read even if you want to use XSL, because it touches on other transformation approaches and sports a rich Resources section.

Tony Sintes is a principal consultant at BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java 2 developer, has worked with Java since 1997.

Source: www.infoworld.com