I'm a Java developer living in Lodz (Łódź), Poland, working for several years with Java EE/Spring platform. As most Java web developers, I started with plain JSPs, went through Struts, EJBs, JSF, and other technologies, in the continuous investigation of the best solution for my job. I'm still searching, but I've already found some pieces of software, which are programmer's masterpieces, like Spring Framework or Ext-JS JavaScript framework. Recently I'm experimenting with RESTful web services and web applications, combining Spring with REST and Ext-JS. Other areas of my interest cover Groovy/Grails, OSGI, and modern build tools. Grzegorz has posted 2 posts at DZone. View Full User Profile

The Death of XSLT in Web Frameworks

04.21.2009
| 39104 views |
  • submit to reddit
Several years ago there was a trend in Java web frameworks to use XML processing as a foundation for the framework logic: take the data from database and present it as XML document (either convert it from relational data, or use XML capable database), and transform it to HTML using XSLT. There were some books written about it, and some frameworks created (like Cocoon). After some time the hype started to decline, and currently virtually no modern web framework apply this approach, I think.

Actually I've never used it on myself, but I liked the idea at that time. It seemed to be clear and powerful. Funny that only now I have a chance to check how it works in practice. And at least now I know why this approach failed.

For two weeks, I'm outsourced to help some company in their web project. They use their own, home-made web framework for this, to talk to their own, home-made document-repository system. Unfortunately, both seemed to be buggy and unstable, though they say that's not the first project they use them in (I can't believe it's true, really). I guess they would be better off using standard Java Content Repository (JSR-170) for implementing documents repository, and some modern web framework instead of their own home-grown one. If they insisted on XML/XSLT transformations, they could use Cocoon. At least there would be more documentation available, and it would be well-tested and stable. But ok, that's not the first company that suffers from NIH syndrome, or guys are simply too lazy or overloaded to look around for other stuff. The interesting point is: how the XML-based processing works in practice? The short answer is: very poor. And the weakest link in the whole chain is XSLT.

XSLT bloat

I won't dare to say that XSLT is worthless - perhaps in some contexts it can be useful, especially for transforming one document tree into another (valid) document tree, i.e. from DOM to DOM. XSLT gives you guarantee that input and output documents will be valid XML - this is crucial e.g. in SOA applications, transforming one document into other documents, to be processed by machines. (X)HTML is a document tree too, at least formally, but from the point of view of web browser to have perfectly valid XHTML is good, but not crucial, and from the point of view of web designer or developer the DOM behind it doesn't matter at all, and making the template valid XML is of no importance. For dynamic generation of HTML pages in most cases it is much easier if you treat the HTML code as a unformatted text, and make a web page template by embedding some special processing directives in such text. This approach was applied by JSP (first with scriptlets, and than with JSTL), Velocity, FreeMarker, and other technologies. Neither of those technologies use the strict XML as template. On the opposite side we have JSPX (JSP using strict XML) - it never caught on and I guess many Java developers have never met it; and XSLT.

I've used a lot of JSPs with JSTL. It wasn't perfect, but it worked. Now I have to do the same with XSLT and it's a nightmare. Things that took me half an hour to do with JSP take several hours in XSLT. This is a list of things I hate the most in XSLT:


   1. Conditional arguments. For example: how to hide the row in table (using different CSS style), based on some CONDITION, with XSLT? See:

      <tr>
<xsl:attribute name="style">
<xsl:choose>
<xsl:when test="CONDITION">
<xsl:value-of select="'visibility: visible'">
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'visibility: collapse'">
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
...
</tr>


      and now the same with JSP 1.x:

 
     <tr style='visibility:<%=CONDITION ? "collapse" : "visible"%>'>
...
</tr>


      or with JSP 2.x:


      <tr style='visibility:${CONDITION ? "collapse" : "visible"}'>
...
</tr>


   2. Nested loops. In JSTL the <for-each> tag has the var attribute, which is variable that gets assigned the current element from the collection during looping. In nested loops, you choose different var names, and you have easy access to variable at any level. In similar <for-each> in XSLT there is not var attribute. You must use additional variables as child nodes, or some other workarounds. Its very easy to get lost.

   3. Every XML-like fragment which is not an actual XML must be escaped. Say you have inlined javascript function which appends row to the table:
    
onclick="append('<tr><td></td><td></td></tr>')"

      This will work in JSP quite good, but will blow up in XSLT with "could not compile stylesheet" message. You must escape each < character:

    
onclick="append('&lt;tr>&lt;td>&lt;/td>&lt;td>&lt;/td>&lt;/tr>')"

      Nobody could understand what is going on here at first look now.

   4. The functional approach applied in XSLT design, instead of the well known (for all programmers) procedural one, makes "thinking in XSLT" very hard. "Normal" approach (JSP, Velocity, etc) takes the HTML template starting from familiar <html><head>...<body>... and looks for special markers, where it puts data from "model". This data can be Java object or XPath-extracted data from other XML. XSLT does it in completely reverse way: it starts with <template match="..."><apply-templates>... so it takes the XML data document first, and tries to manipulate its content to obtain other document. As I said, in SOA processing this is fine. But in HTML generation it looks completely alien. I must say I always had problems with mental visualization of this process.

   5. No formal XML schema for XSLT 1.0 exists. At least I couldn't find it - there is only unofficial DTD somewhere. This ruins IDE code completion abilities. And the XSLT is so complicated, that you can't simply learn it in one day (or even week), so some inline-help would be of real help.


Now take all those points together and multiply be all the places on the web page where dynamic content generation happens. Lengthy, complicated, with all those escapings, plus complicated XPath expressions, plus this "other-way-round" functional approach. That is developer horror. And worse, it is maintainer hell. In the current project, after two weeks I'm not able to understand the sections I have written a few days ago. I cannot imagine looking at it after several months. What's worse, the template code is so different than resultant HTML code, that navigation in the template and finding the actual place I need to edit takes always too much time.

After two weeks I'm fed up with XSLT. It's absolutely unproductive in web frameworks. Now I know why none of XML-based frameworks got big popularity ever. And I know I was completely wrong 3 years ago when I could bet that in the short time JSPX would replace JSP. Fortunately, it didn't.

Any alternatives?

Now that we know XSLT is evil, which view technology should we use in our projects? Stick with JSP? For JSF-based project I wouldn't use JSP for sure, because it simply doesn't play well with JSF, and instead I would go for something like facelets. But actually I wouldn't go for JSF either any longer (that's another story about the thing I used to believe in and predict long life to it, and that I was finally disappointed completely with). So for non-JSF projects there are JSP/JSTL, Velocity, FreeMarker, GSP for Grails projects, SiteMesh for page layouts, perhaps other technologies that I'm not aware of. JSP/JSTL is the most widely used, best known, and has best tool support, even if it is probably the worst one from the group. Take those crazy SQL-based tags in JSTL, or funny standard tags from JSP to deal with request parameters. Whey didn't they just took those tags from JSTL that are used always (if, for-each, format, ...) and make them part of standard JSP? Why I always have to include it as separate library on Tomcat? Besides, I said earlier that the actual input template doesn't have to be valid XML, but I must say I don't like constructs like <input value="<c:out ...>">. Tag inside other tag's attribute - this looks horrible. That is why now I think that template directives should not be constructed with XML tags: so all those custom tags, JSTL tags etc is the wrong direction. Such code is simply too hard to read, because it resembles too much HTML (ok, templates not always are used to generate HTML, but I guess in about 95% of cases they are). The better approach is to use some special characters, like # directives in Velocity, or [# in FreeMarker, or EL syntax ${...} in JSP/JSTL (but EL is too much limited and it is actually not directive; besides assumption that only getters can be called from EL was serious mistake: e.g. you cannot check collection size, because there is no getSize() method, only size()). Compare the if-then-else block created with JSP/JSTL:

<c:choose>
<c:when test="${expr1}">
...
</c:when>
<c:when test="${expr2}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>


with the same written with Velocity:

#if (expr1)
...
#elseif (expr1)
...
#else
...
#end


Which one is easier to read?

FreeMarker can be also good replacement for existing projects that already use XSLT. From what I see, you can bind the XML data document to some variable, and then access it with XPath queries from FreeMarker template to extract data. Velocity offers similar thing, it's called DVSL, but I doesn't look good to me, because it applies the same functional, other-way-round-alien-looking "apply-templates" approach as XSLT.

Velocity or FreeMarker integrates also well with Spring. Form my point of view, the only serious drawback of those technologies when compared to JSP, is IDE support. In the company where I do my painful job with XSLT, "the only IDE" is NetBeans (I think it is not obligatory, but simply all guys use it and all projects are not build with external Ant script or Maven, but simply by NetBeans, so it is hard to use other IDE anyway). I tried to find some plugin with Velocity or FreeMarker support for Netbeans (at least for syntax highlighting), but looks like there is no one. That's really strange for me - those technologies are on the market for many years, and are quite popular I think. So why there is no support in second most popular Java IDE for them? For Eclipse the situation is better, from what I see.

So if you start new project, think twice (or ten times) before jumping into XSLT. And if you use Eclipse, you can even think twice before using JSP/JSTL. Velocity or FreeMarker might be a better option.

Published at DZone with permission of its author, Grzegorz Borkowski.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Ingo Maas replied on Tue, 2009/04/21 - 2:51am

Nice article. Of course, one has to choose the right tools to get things done. XSLT 1.0 is indeed awkward, but XSLT 2.0 is a lot better (for transforming pure XML). BTW, Eclipse has upcoming support for XSLT code completion, see the WTP XSL Tools project. I don't know about NetBeans in this case.

Julian Warszawski replied on Tue, 2009/04/21 - 3:01am

I could not agree more on how annoying can implementing presentation layer with XSLT be.

But unfortunately, I cannot agree that the tool is dead by now. From time to time I have a questionable pleasure of dealing with XSLT hell because the company i currently work in uses the EMC Documentum system for internal document management. Even the newest versions of Documentum still use (and promote the use) of XSLT as a way of implementing presentations in portal environments.

And you wouldn't believe what sort of tasks are realised in our *.xsl files. Database querries and operation on files are just a few of them. But that's what is commonly called "Vendor Lock-In".

Alexander Shirkov replied on Tue, 2009/04/21 - 3:28am

Eclipse has excellent plugins for FreeMarker development. It contains autocomplete, syntax highlighting. I've used it, when do some works in Struts 2 (it uses FreeMarker to render tags).

Danny Lee replied on Tue, 2009/04/21 - 4:09am

Once I was "forced" to use XSLT in one of tasks. It was kind of horrible. After a while the complete solution (and it was damn complex) had to be redesigned, so you can imagine how happy I was about it. Then our designer guy said: what? It's just XML & XSLT? Can do! So after all it was kind of good solution. 

And don't forget, that XSLT has more dynamic than JSP/Struts/etc, you can hold it in your DB or configuration pool and change it as you like. 

Olivier GERARDIN replied on Tue, 2009/04/21 - 6:01am

I agree about the XSLT bloat, but once you get to work with it for a while, you begin to see the beauty of it. Or not, as you seem to suggest. I had to work with it and I had a lot of fun. I even wrote a XSLT compiler that would generate C++ code from a XSLT template, that you could then compile into a standalone executable (sources still on sourceforge: https://sourceforge.net/projects/xsltc/)

Actually your point 4 is not correct, a XSLT template doesn't have to use <template> as its root element, it can use a literal result element as root, which is closer to what you're used to see if you've worked with JSP or other template engines: see http://www.w3.org/TR/xslt#result-element-stylesheet. Furthermore, XSLT being functional, the "natural" structure of a function (or template) is the result's structure, not the underlying XML model.

Anyway, I have to agree that even a properly written XSLT takes a lot of effort to read and understand, and is much too verbose (and I'm not even talking about XSLT templates written by beginners).

XSLT will stay because it's still the best way to transform an XML document into another XML document, but its definitely not well suited for hand-written HTML templates.

 

My blog:http://blog.gerardin.info

Jess Holle replied on Tue, 2009/04/21 - 6:55am

Sure XSLT is verbose.  No question.  It would also be nice to see a solution to #1 in XPath.

As far as #3, XSLT insists on being valid XML -- the JSP example shown is not and gets equally ugly if one uses the XML form of JSP (.jspx).

Personally I find NetBeans makes editing XSLT pretty easy and am used to the escaping business from Ant, etc, anyway.

The only bloat I'd actually get uptight about is that at runtime which is inherent in any in-memory tree/graph model for dealing with XML.  This goes for DOM or any DOM-like model.  Sometimes you need a complete object tree/graph model of the whole document in memory at once for random access, etc.  In that case, XSLT and DOM-like models aren't adding any bloat.  For all the other cases, these approaches add an unnecessary scalability bottleneck by pulling the entire document into memory at once rather than doing streaming processing of the document.  That's fine as long as all documents are small, but less fine otherwise.

The XSLT specification does not dictate an in-memory tree/graph model, but some of its features practically necessitate such an approach.  What's maddening is that no XSLT implementation that I'm aware of does sufficient static analysis of the XSLT to determine whether a non-streaming approach is required or whether a streaming approach with a bit of look ahead or remembered state would suffice.

All that said, XSLT can be quite convenient at times.

Ivan Lazarte replied on Tue, 2009/04/21 - 10:22am

I'll flat out say what other ppl are afraid of saying- XSLT is awesome. You can set up chains of transformations that take a simple input doc and get radically different (and VALID ?! omg a VALID web doc?!) outputs.

I was a jsp addict that lived off of the easy no-hassle beauty of Tiles and .tag files for simplicity and presentation; but after I learned Xslt I looked for a plcae to insert it.

Here's what I made with it (on my own time):
1. an Xslt-based code generation system. Xml to Sql/Jsf/JavaBean.
2. an data tranformation layer - Xml to Java, Java to Xml (runtime, no compiler needed) and other plugins like Csv and Json.
3. Finally, a simple presentation layer. A simple system of piping one xml output to another to achieve presentation goals.
All of that achievable outside of a servlet container, validateable code via Xsd (not some arbitrary language like Jelly) and useful stuff. How can you argue against a language (dialect?) designed for transformation? I found that where Jsp would get harder towards the end of a set of display requirements, xslt finishes with ease and a flourish.

Other positives include simple Java enhancement (referencing a static Java function is trivial for example) and even potential runtime modification of your transformation layer!

Why did it lose mindshare in the end? Probably the same reason I hated it initially.
1. Novice Xslt is verbose, and ill-organized.
2. It's a very different mindset. Ifs and Foreaches really aren't needed if you know what you're doing. Everything should be based on selection instead which factors out iteration and conditionals in favor of selected sets.
3. It's slow (in theory). In reality, you never directly serve content to the user for large-high volume sites anyway. It's hidden behind layers of caching. For small websites that isn't an issue, so where's the performance problem?

I dunno. I'm one of the few people looking forward to Cocoon 3 - I think Xslt still has a bright future - just not as a Jsp clone. Another issue is no one seems to learn it anymore. I learned it completely off hours, but it was a pretty cool experience.

Ben Hardy replied on Tue, 2009/04/21 - 12:09pm

The fundamental problem with XSLT is the fact that it is XML itself - and XML is simply a lousy language for writing any kind of instructions or code. And XSLT represents instructions for transforming XML. Therefore in my mind it's as bad as Jelly, and nobody likes dealing with that either.

XSLT needs to be replaced by something that isn't expressed in XML.

 The fact that you can write Java code using SAX or DOM to do the same thing far more clearly and far less verbosely speaks volumes. In fact, I'm surprised nobody's come up with a nice Scala DSL for XML transformation already (not that I've really looked for one yet).

 

jochen rebhan replied on Tue, 2009/04/21 - 1:36pm

Comparing xslt1 (xalan for example) and xslt2 (saxon.sf.net for example) is like comparing C and Java. Maybe there are some syntactic similarities, but under the hood there is for example a complete different type system and much more functions which make every days tasks much more easy.

 

 

 

Zdenek Machac replied on Tue, 2009/04/21 - 2:41pm

In XSLT 2.0 is posible your example in XSLT 1.0 rewrite to

<tr style='visibility: {if (CONDITION) then "collapse" else "visible"}'>
...
</tr>

 

XML Schema for XSLT 2.0 exist at:

http://www.w3.org/2007/schema-for-xslt20.xsd

 

For Netbeans exist great FreeMaker plugin which was mentioned in dzone.com page

http://java.dzone.com/news/freemarker-netbeans-ide-60-first-scenario

 

Jose Maria Arranz replied on Tue, 2009/04/21 - 2:54pm

XSLT was a try to create a "XML-to other format" transformation executable language in declarative form.

XSLT in essence is not fully different to executable custom tags in JSP or JSF or any other custom tag based executable templating solution. The main difference is "the language" (for instance EL) and/or rules of any other custom tag solution are more customizable and powerful including Java accessing than XSLT "executable tags", and executable templates are usually more imperative than XSLT (because XSLT is pure declarative).

In regards to "Now that we know XSLT is evil, which view technology should we use in our projects?"

I invite you to try ItsNat, I think it can be useful in your project because it seems heavily based on XMLs and using XSLT to generate HTML.

 ItsNat uses pure XHTML templates in server, these templates are converted to DOM, with DOM you can do any kind of view logic and in an AJAX environment any change to the DOM in server updates the client automatically using AJAX. Static parts of the DOM tree can be cached as plain text shared between users saving server memory, the framework takes care of sending the cached pieces when the tree is sent to the client.

 I think you could reuse your XSTL files and convert them to pure XHTML ItsNat templates removing XSLT rules. 

 Then load your XML files as text and convert to DOM using the method ItsNatDocument.toDOM(String) (XML header should be removed manually before), in spite of ItsNat DOM Document is X/HTML, non-HTML tags can be parsed and converted to DOM.

 Now the XML is DOM, DOM format is by far easier to manage than XSLT to process it and now you can traverse this DOM tree and extract any data. The data could be inserted into the XHTML DOM tree in the server (managed by ItsNat reusing your XSTL), optionally using ItsNat components, because ItsNat components use a pattern approach in some way similar to the layout patterns of XSLT (the main difference is the view logic is not in the template).

 

Daniel Lopez replied on Tue, 2009/04/21 - 3:00pm

After two full weeks of working with it you came with the conclusion that a whole technology is wrong? Man, that's being pretty confident. I wouldn't dare having such a strong opinion in a such a short time, but oh well :).

Joking aside, you could, for example, write number 1 as:

<tr style="visibility: collapse>
<xsl:if test="CONDITION">
<xsl:attribute name="style">visibility: visible</xsl:attribute>
</xsl:if>
    ...
</tr>

Which is less verbose, you might have to resort to xsl:choose if there are more than two options, but the equivalent JSP would not be that short also.

In any case, I think your problem is simply that you are not used to XSLT and you blame it for not being what you are used to. Like any technology, it has its advantages and its drawbacks and yes, it's way too verbose and the "functional flavour" that it has is pretty new for many programmers and sometimes makes for quite cumbersome code. But it also has many advantages that we've enjoyed for about 11 years, since we created our framework (at the beginning of 1998, almost one year ahead of Cocoon) and we are still using it.

We added recently the possibility of using FreeMarker to process the XML, as it allows non-well-formed templates, but to tell you the truth, for many tasks we still employ XSLT because once you get used to it, it makes some things pretty simple and you know which things to avoid.

To think that just because it does not work for you, I would say you have had no time to really know if it does or not, or you don't like it, it means the technology sucks... well, one must think his own opinion represents the whole industry. We know we are not that big, so we know that even if it does work for us, it does not mean it will work for anybody else. And viceversa, if we don't like something because it does not fit in "our scheme", we don't think it sucks. May be it works for some other people.

In any case, I'm not going to "sell" XML/XSLT to anybody. It has worked for us and it still works for us, period. You can use whatever you want, we'll do the same ;).

Cheers

Daniel Lopez replied on Tue, 2009/04/21 - 3:06pm in response to: Ben Hardy

You mean something like this? (xsltxt.dev.java.net)*

The project seems to be stalled, however :(.

 

* Cannot write the address with https because forum thinks it is spam and no captcha image is displayed :(

Tjerk Wolterink replied on Tue, 2009/04/21 - 3:37pm

I generally disagree with your (narrow) view:

Point 1: Its a matter of taste. Ok there is a lot of xml, however the whole document is one XML file, it has one tree structure. Also: youre not bound to a specific xslt implementation. This is a advantages.

Point 2: What is the problem with explicitly defining a variable? Also a matter of taste.

Point 3: That a feature: XSLT ensures xml output. onclick="append('')" is invalid

Point 4: Functional programming is better for templates i think. Pattern matching is really good. I just say: for all objects of Type x using this template. If you never did some big project in a functional programming language it is difficult to grasp, i understand that. However once you ate from the cake you cannot get enough. Functional language are at a higher level then most procedural languages. Programming in a functional language requires a change in the way of thinking for a programmer. All in all i would say the functional aspect of XSLT is a plus.

Point 5: Still a subjective argument. What do you mean with "formal". XML SChema only defines the structure not the semantics. Is the semantics of JSP that formal? This discussing gets really deap and can be about (programming) languages in general. And also: there is XSLT 2.0


XSLT is not evil in general, only iin your subjective view. I have used it a lot for websites. And the only legal disadvantage is speed: XSLT execution is much slower than jsp execution.


My view: XSLT is really powerful: XPath is also part of XSLT and is also really powerfull. But beware: if your data is not xml its maybe better (performance wise) to use a template engine that uses pojo's.

However if you integrate different systems you often invoke webservices wich output xml, this xml can be aggregated and with XSLT you can give an XHTML view to the user. So if you have got a lot of XML data XSLT is the way to go.

As with a lot of things in computer science: It all depends on the requirements.


The general problem with a lot of programmers is that they just do not like XML: it is bloatware. Well it has to be bloat because there where a lot of requirements for XML: it has te be extensible, etc etc etc. XML is just really powerfull. It is difficult to make it that powerfull without making it bloat (namespaces etc).

Kurt Cagle replied on Tue, 2009/04/21 - 6:33pm

Grzegorz,

I've worked with XSLT 1.0 and 2.0 for the last decade, have written books on XSLT and have talked extensively about XSLT at dozens of conferences.

For what it's worth, XSLT (especially in the 2.0 incarnation) is exceptional at what it does, which is transforming content from XML (or HTML, depending upon the version and implementation) to other formats. I cannot think of any imperative language, Java included, that has the power that it does to do that task.

However, by your description, you're using XSLT as a screwdriver to pound in a nail. If you are working with XML in the way that you're describing, consider using XQuery. It is much less verbose, is extensible, can be cleanly invoked from any number of Java implementations, and is remarkably effective at pulling content out of XML repositories, data streams and even relational databases. Certain implementations can even give you access to server environmental variables and content, can let you invoke SMTP and similar processes, and can be extended with your own custom classes.

Before condemning a tool, learn how best to use it. 

 

Kurt Cagle

Contributing Editor, xml.com

Managing Editor, xmlToday.org

 

Bill Sorensen replied on Tue, 2009/04/21 - 8:03pm in response to: Ben Hardy

Amen!

I used XSLT on a non-web project several years ago, believing it was the right tool for the job. It worked, but had a high learning curve. I've since regretted it, as no one else wants to maintain the XSLT. I agree with Mr. Hardy - XML is not the best medium for writing code (especially recursive code).

Ronald Miura replied on Tue, 2009/04/21 - 10:44pm

One interesting use of XSLT is to delegate formatting to the client. The server generates only presentation-agnostic XML, including a XSL declaration. The transformation into XHTML is made by the browser.

http://www.w3schools.com/XML/xml_xsl.asp

This way, you could:

1. make the server result completely independent of the client (or, limit it to just switch the XSL declaration), making it potentially easier to support many different types of clients.

2. save server resources, since you generate just plain XML, which is probably much simpler and lighter than a formated response.

Absolutely not the right tool for all problems, but an interesting one for some.

Carsten Saager replied on Wed, 2009/04/22 - 2:08am in response to: Ben Hardy

The reason XSLT is in XML is that you can write XSLTs by transforming XSLTs -  it is like Lisp's Code is Data. In such a context mutables like in imperative programming don't work too well.

A better syntax wouldn't do any harm, I personally like Lisp better than XML (Lisp is conceived to be read by machines, XML to be written by machines as well)  but the main difference is that XSLT isn't functional but declarative. This makes several things very concise, but many tasks pretty awkward or at least naturally obfuscated.

Last year I had been asked to do a quick hack of a data-transformation while the "A-team" is doing the "proper and complete" solution. At its core their strategy was based on "just some XSLTs". From previous XSLT-programming I knew that this would be difficult and therefore I hacked something in a functional language. After three days I had a prototype and with a little extra work it did everything we wanted from it. The A-team never delivered anything.

In the end it is like with Prolog: You do also have to shape your problem to fit the language.  That usually works poorly in a context like interfacing

Grzegorz Borkowski replied on Wed, 2009/04/22 - 2:38am in response to: Kurt Cagle

Kurt,

Thanks for pointing to XQuery. To say the truth, I don't know it very well - probably because I've never seen it used in any "real" application (not counting tutorials or so). And I always associated XQuery with database queries, not with HTML templating. But you're right -  quick search returns for example this page: http://www.w3schools.com/xquery/xquery_flwor_html.asp with the XQuery HTML templating sample. It's a matter of taste, but for me it looks better than equivalent XSLT code (just the first impression). Looking at this sample I'm not sure how this transformation is actually done, by what tool etc., but this is a detail - it must work somehow, I guess.

And to make things clear (for all other comments):

1. I didn't say XSLT is evil in general. Quite opposite: it's probably best tool for XML-based SOA transformations. But it is the worst tool for HTML templating (plus the slowest one).

2.  The XSLT's functional approach requires much more time from Java developer to learn it. It's always good to learn new tools, techniques etc. But it's impossible to learn them all."Typical" Java developer (like me) doesn't know functional programming well, so he will not be able to take advantage of XSLT. So if you decide to use XSLT in your project as HTML templating, you'll probably loose on people's productivity.

3. Also the context depends on how you obtain the XML. If you have already existing XML (obtained from web service, from file, from XMLDB...), then JSP will be of little usage, and XSLT is natural choice - but still in such  a case I would look at FreeMarker first, as i mentioned in the article, it's XML-capable and seemed to me much easier to learn than XSLT. But if you retrieve relation data from database, map it to Java objects, then represent it as XML, then transform it to HTML - than it makes no sense for me (and this is a case I am involved in recently, unfortunately).

Michael Havard replied on Wed, 2009/04/22 - 10:34am

Sorry Grzegorz but those are horrible examples and really just show why Java developers struggle with web development in general. XSLT isn't evil, you've just failed to take 2 minutes to do a google search and find the right way to do it, and failed to put the same effort forth learning the language that you took to learn JSP.

In the last decade I've seen a lot of Java developers who just want to hack something together and throw it out on the web without understanding best practices, without wanting to keep their HTML, JavaScript or CSS skills up to date and without worrying about future maintainability.

More than one of your examples could be done more efficiently using client side JavaScript either hand coded or using one of the many popular libraries like JQuery. Unobtrusive JavaScript and graceful degredation are not new concepts to web development. Doing things like inserting copied nodesets like your table row example should be kept out of the HTML and definitely out of the XSLT.

<tr>
<xsl:attribute name="style">
<xsl:choose>
<xsl:when test="CONDITION">
<xsl:value-of select="'visibility: visible'">
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'visibility: collapse'">
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
...
</tr>

 or

<tr>
<xsl:if test="CONDITION"><xsl:attribute name="class">collapsed</xsl:attribute></xsl:if>
...
</tr>

Keep the style out of the HTML and rely on the HTML structure, classes, or id's to attach style information via external CSS files. This makes it much easier to maintain as you move forward. In this case the default tr style is visible - no need for any code, while the matched condition adds the collapsed class.

In many cases you can avoid using loops and especially nested loops by leverage template matching, which it sounds like you struggled with understanding. There are also a few techniques using keys to create grouping, which is typically what people are doing when they are nesting for-each loops. 

I always point people just learning XSL to the XSL FAQ at www.dpawson.co.uk/xsl/sect2/sect21.html and the XSLT Standard Library xsltsl.sourceforge.net/#id1954924. Just like with JSP there's no reason to reinvent the wheel every time you develop. If one of those two sites doesn't have the solution you need then you're probably doing it wrong. Beyond those two sites there are plenty of books on Amazon for XSLT.

I've trained close to 100 java developers over the last decade on how to use XSLT. All but a few picked up on it fairly quickly a good quarter of those 100 ended up preferring XSLT over JSP in the end. The biggest hurdle in transferring someone from JSP to XSLT is breaking them of all the bad habits they picked up from JSP. We use Spring MVC, Spring WebFlow, Castor, and XSLT - development is fast and lean and we see much higher code quality than we did when we were using JSP.

 

Maxim Gubin replied on Wed, 2009/04/22 - 10:37am

I've had the opportunity to work with XSLT at my job and I did not like it, nor did the business.

For one, it was extremely slow.  Some of our XMLs that it would render would take 10 minutes or more.

They were around 10mb xmls.

The other issue, is that it is a pain to maintain or try and do things with it.  It's like pulling teeth.

 

I was tasked to create an alternative solution that would be more performant.

I looked into 3 alternatives.

1) Using a custom java class that would render the xml based on the builder pattern.

That wasn't so bad, but this class was very basic and just did not have many of the features that we might need such as xml escaping, language support etc.

2) Groovy's MarkupBuilder

That was really nice to use since the syntax of Groovy's builders is so clean.

3) FreeMarker

This kind of caught me by surprise.  The templates are very easy an intuitive to setup, plus you get all of the goodies that FreeMarker framework offers and you get to use your custom Java code if you're so inclined.

The performance was improved dramatically in all 3 cases.

The custom Java class performed way better than the Cocoon (XSLT) implementation.  It had issues with unescaped strings etc.

Groovy's MarkupBuilder suprisingly was slightly faster than the Java implementation.  It was hard to refuse using it, since it was so nice and clean.

But FreeMarker ended up blowing all of these out of the water.  Its performance was about 10x quicker than either of these solutions and on a magnitude of 30x+ more performant than XSLT.

Plus the templates just look so nice and clean.

I ended up writing a custom framework that is managed by Spring (DI) and uses FreeMarker under the hood.

The reason for this being that we wanted to do certain business logic per request depending on the type of a feed this was.  For example, in one case we did some metrics gathering before the request and then passed on that result to the FreeMarker template.

So we could have opted to simply use FreeMarker outright as the view layer, but since we needed this custom business logic to be injected for some requests, we used a wrapper around FreeMarker to do this.

I also implemented the Ehcache solution to speed up the rendering even more.

Maybe some day I will open source it, but first I'd like to introduce Spring AOP in order to make the separation of concerns a priority.

Michael Havard replied on Wed, 2009/04/22 - 10:56am in response to: Maxim Gubin

I hear a lot of people complain about XSLT performance and it's almost always because they're parsing large files when they don't need to. The sites I work with have hundreds of pages using XSLT and render/response times are sub-second and display hundreds to thousands of data points coming off of multiple back ends.

Can I ask why you're producing a 10mb XML file?  Castor, XStream, JAXP, JIBX and several other tools can marshal your Java objects to XML more efficiently than creating your own classes.

 

Patrick Schriner replied on Wed, 2009/04/22 - 11:38am

If you try to emulate iterative behavior with XSLT you are of course under the impression that it is a failure.

XSLT is awesome when you use it to it's best - for recursive algorithms, and as a declarative language.

The possbility to combine declarative and iterative programming is one of the strengths of XSLT, as are it's inherent type system and buildin functions.

Colin Toal replied on Wed, 2009/04/22 - 12:05pm

I have to say I disagree with a good deal of this article. Most of the issues are really minor aesthetic concerns. Why does XSLT have tag based condition expressions ? I mean - its not important is it ? Its more readable than the ? : operation - but everyone other than me stopped complaining about this assinine operator years ago. These are not discussions worth having. Point 4 is the biggest difficulty with XSLT development in the list. XSLT is hard for programmers used to procedural programming. XSLT is much closer to a functional language, and most developers working with it are .NET or Java developers who think procedurally. In general, it may be easier for people to think procedurally than functionally, but I think that once you make the leap (a leap many people make with SQL but do not really appreciate because of how little they actually use of it) - XSLT really becomes very interesting and novel. The upside to functional languages is that they are really easier to test and prove correct over a wide range of inputs. Also, they can be truly parrallelized without any of the nasty locking and mutual exclusion code that multithreaded procedural programming needs.

Henry Ho replied on Wed, 2009/04/22 - 8:15pm

Any alternatives?

How about ColdFusion?  It can talk to JSP pages too. :)

<cfoutput>
<tr style='visibility:#Iif(CONDITION,"collapse","visible")#'>
...
</tr>
</cfoutput>

 

Interoperating with JSP pages and servlets

ColdFusion pages and JSP pages can interoperate in several ways:

  • ColdFusion pages can invoke JSP pages and servlets.
  • JSP pages can invoke ColdFusion pages.
  • ColdFusion pages, JSP pages, and servlets can share data in three scopes.

Lars Huttar replied on Thu, 2009/04/23 - 3:52pm in response to: Jess Holle

What's maddening is that no XSLT implementation that I'm aware of does sufficient static analysis of the XSLT to determine whether a non-streaming approach is required or whether a streaming approach with a bit of look ahead or remembered state would suffice.

Have you looked recently at Saxon's static analysis and streaming features?

Saxon-SA has a facility to process large documents in streaming mode. This enables documents to be handled that are too large to hold in memory (it has been tested up to 20Gb). (saxon.sourceforge.net)

I haven't used those features myself.

Lars Huttar replied on Thu, 2009/04/23 - 4:47pm

Grzegorz,

The death of XSLT is greatly exaggerated. In our team we have developed a variety of internal web-based apps that continue to be in production, and we are continuing to develop more using the same model. Our framework is Cocoon and XSLT is our main "programming language" if that is the term to use.

Yes, XSLT has a steep learning curve. But it also does the things it's designed for more easily than any other language.

Yes, XSLT can be verbose. But not in the way that your examples show. The verbosity there is the result of not knowing how to use XSLT very well; you're comparing bad XSLT with decent JSP. And as others will point out, XSLT 2.0 is much less awkward than XSLT 1.0. Taking your first example, which you rendered in XSLT as:

<tr>
<xsl:attribute name="style">
<xsl:choose>
<xsl:when test="CONDITION">
<xsl:value-of select="'visibility: visible'">
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'visibility: collapse'">
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</tr>
Put that way, of course it's awful. Aside from the fact that the above is not even well-formed XML, some elementary knowledge of XSLT 1.0 would give you
<tr>
<xsl:attribute name="style">
<xsl:choose>
<xsl:when test="CONDITION">visibility: visible</xsl:when>
<xsl:otherwise>visibility: collapse</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</tr>
which is more reasonable. And XSLT 2.0 would give you:
<tr style="visibility: {if CONDITION then 'visible' else 'collapse'}">...</tr>
... essentially equivalent to your JSP. (There are also tricks to get similar syntax in XSLT 1.0.)

I would recommend reading up on basic concepts of XML, such as well-formedness vs. validity. This will enable you to evaluate XML-related technologies like XSLT from a position of understanding. It will also give your writing more credibility. For example, you say above that "XSLT gives you guarantee that input and output documents will be valid XML", but this is not true in general. Maybe you mean 'well-formed' instead of 'valid'. It is true that a validating XSLT processor (like Saxon-SA) *can* validate its input, but it's not a central feature of XSLT, and common XSLT processors/frameworks don't support it (you'll be hard-pressed to make it happen in Cocoon). It can just as easily be done by a separate tool in the pipeline.

Your points 1-5 have been commented on somewhat, and I'm tempted to respond to them individually, but I'd better get back to work for now.

One last thing:

Things that took me half an hour to do with JSP take several hours in XSLT.

I hate to sound ungenerous, but that is probably more your fault than XSLT's. It is bound to be the case when you use a complex language that you have not learned much about. This is especially true in XSLT. Yes, I agree XSLT is a harder language to learn to think in than your usual procedural language. And as such, XSLT is not the best tool for every programmer nor for every task. More than most languages, you have to learn a number of non-obvious principles before getting to the point where you can write code that does what you expect. But it doesn't make sense to disparage XSLT just because you're forced to use it without adequate training.

For those who have been fortunate enough to learn XSLT well, and who work on tasks that XSLT is suited for, the investment often pays off very handsomely. I use XSLT for a whole gamut of tasks, even fairly trivial ones, and I enjoy it. I would dislike having to do general XML-to-XML transformation in a procedural language.

XSLT is much more useful now than it was a few years ago. It's a staple for our web application development team, and people from other departments are always working on XSLT projects as well. I can't predict the direction of the industry, but I hope XSLT 2.0 will be more widely understood and supported -- and used for appropriate tasks. It would be sad if this very useful tool were spurned because it was found difficult to use without reading the instructions.

Laura Porter replied on Fri, 2009/04/24 - 5:05am

You're writing this completely from the view of using XSLT1.0 & XPath1.0, which are 10-year-old standards. Have you used XSLT2.0 & XPath2.0? Your example #1 can be easily re-written as:

tr style="{if (CONDITION) then 'visibility: visible;' else 'visibility: collapse;'}"

...along with  many, many other examples.

 It might be useful to learn a little more about a technology before completely dismissing it!

 I've been using XSLT for more than 9 years, and I find it far easier to write than any other language. This is down simply to the fact that I've made the effort to learn about it thoroughly.

I think the same could be said of learning *any* programming language. 

Laura Porter replied on Fri, 2009/04/24 - 5:09am in response to: Colin Toal

XSLT is hard for programmers used to procedural programming. XSLT is much closer to a functional language, and most developers working with it are .NET or Java developers who think procedurally. In general, it may be easier for people to think procedurally than functionally

 

This is definitely where I'm lucky, as I learned XSLT *before* I started learning procedural programming (I have no formal IT-related training). But as you say - once you can move your brain away from procedural programming thoughts, XSLT really does become clear. I've taught XSLT to many people over the years, and I have yet to meet anyone who wasn't impressed with what it - especially 2.0 - can do, once they'd got their head around it.

Grzegorz Borkowski replied on Fri, 2009/04/24 - 4:19pm in response to: Laura Porter

Well, thanks for all your constructive comments pointing my faults. A few words of explanation: first, the code of choose-then-else is really not well-fromed, the elements are not propery ended. It's strange, as I thought I've copied it from working template. And in fact the xsl:value-of is not needed in this case. Perhaps I've copied it from somewhere and didn't noticed it can be simplified. Still, the construction is awful in XSLT 1.0, but looks good in 2.0 version. And I know the difference between well-formed and valid document :) but simply as XML is not my primary area of work, I'm not so sensitive to semantical differences in this context.

I know far less about XSLT 2.0, as this is relatively new technology, and when I learned XSLT it was not out yet - and I don't observe the changes in XML technologies as closely as in Java case. Also there are far less 2.0 examples on the web. And finally, the framework I have to use at the moment uses JRE build-in Xalan, which is not 2.0 capable, AFAIK. Correct me if I'm wrong, but I guess they would have to switch to Saxon to use XSLT 2.0 (are there any other parsers available?). This is probably not a big deal, but in this project it is not me who decides.

But I said earlier, most Java web developers will be probably in similar position to me: they usually know JSPs quite good, and XSLT only on basic or medium level. It's hard to make all of them XSLT masters. It will be much more efficient and productive to stick to JSPs or switch to tool like FreeMarker, which they can learnn in about one day.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.