Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Why XSLT and not just Perl?

by blahblah (Friar)
on Jun 14, 2003 at 17:47 UTC ( [id://265926]=perlquestion: print w/replies, xml ) Need Help??

blahblah has asked for the wisdom of the Perl Monks concerning the following question:

I recently started tinkering with XSLT. After a short while it occurred to me that I could do everything in Perl using XML::Simple or XML::Twig or XML::SAX and a bunch of print statements that I'm currently trying to do in XSLT. Conversely, I could do much more in Perl by using Perl's data structures and functions, without loosing the benefit of content separated from formatting since my data would still be in XML.

This led me to start trying to come up with a specific list of benefits of XSLT versus simply making "templates" in Perl, but I could only really think of Perl Pros.

Perl Pros
  • A lot easier to debug
  • Seems to be faster, although I havn't benchmarked anything.
  • More examples to learn from.

So I'm trying to wrap my head around why anyone would use XSLT. It just seems crippled compared to more robust languages (if XSLT can be considered a true language since there are no for or while functions, only for-each). I feel like I'm missing something, but I don't know what. What would a good real world example of why you would use XSLT over Perl?

Thank you for your thoughts.

Replies are listed 'Best First'.
Re: Why XSLT and not just Perl?
by Arguile (Hermit) on Jun 15, 2003 at 01:52 UTC

    Many good points have been raised about why XSLT exists, I won’t rehash them. I’d like to focus on this specific statement:

    It just seems crippled compared to more robust languages (if XSLT can be considered a true language since there are no for or while functions, only for-each).

    XSLT is not meant as a procedural language. Lisp, Scheme, Haskell, Prolog; are these not programming languages because they don’t include procedural loop constructs? When you create an XSLT document (script? program?) you don’t worry about the how of it, you just say what you want done. XSLT is a declarative language, and it's power lies in that.

    A great example of the difference is an answer to a question asked today. Granted it’s a trivial example but it illustrates a larger point*.

    # Copied from node 265898 by valdez. Cut and modified slightly. use HTML::TokeParser::Simple; use HTML::Entities; my $parser = HTML::TokeParser::Simple->new( 'filename' ); my $in_body = 0; while ( my $token = $parser->get_token ) { if ($in_body) { # we are inside BODY if ($token->is_text) { # it's text, convert it print HTML::Entities::encode_entities($token->as_is); } else { if ($token->is_end_tag( 'body' )) { # we've found the end of the BODY $in_body = 0; } print $token->as_is; } } else { if ($token->is_start_tag( 'body' )) { # we've found the beginning of the BODY $in_body = 1; } print $token->as_is; } }

    Notice all the how bits; variables controlling when to loop and when to stop looping, the loop contructs themselves, conditionals to see if we’re in the tag or out of it, etc. Notice also that the program resembles the layout of the HTML document. What happens if the elements we want are three deep? Four? What about multiple distinct operations? Specification changes?

    Now let’s look at an XSLT example of the same procedure (we’ll just imagine the encode_enties function exists):
    <xsl:stylesheet version="1.0" xmlns:xsl=" +ansform"> <xsl:template match="body//text()"> <xsl:value-of select="encode_entities(.)"/> </xsl:template> </xsl:stylesheet>

    None of the how is needed in XSLT. You simply state what section of the document you’re interesetd in with XPath, what to do there, then apply the directive. Gone is the overhead (pre-amble, variables, loops, etc), the ties to the document structure, and problems with adding new rules. The how has been removed.

    I'm not saying XSLT is the be-all or end-all, but it fits it's problem space well. Not being procedural can be a strength, you just have to learn to use it.

    * Please note I'm not in any way insulting the answer, ‘trivial’ refers to the scope of my example.

    Note: This obviously isn’t the only way to do XML transforms in Perl. However, it does illustrate (I hope) some of the differences between general and task based languages, as well as procedural vs. functional/declarative approaches.

      In fact the difference you are showing stems from 2 things: mostly that XSLT uses a tree-model while HTML::TokeParser::Simple uses a low-level pull model. The fact that XSLT has an encode_entities function instead of the longer HTML::Entities::encode_entities also makes the XSLT code look nicer.

      Using a tree-based module, XML::LibXML or XML::Twig for example, would lead to code that would look very similar to the XSLT one.

      As for the vaunted difference between what ("state the section you want") and how (select the section you want by navigating, or by using XPath)... frankly I don't see whatthe big deal is.

        Since you bring it up - I though that XSLT was normally handled by SAX which I didn't think would be normally fed into a tree structure. Or is XSLT going to always be stuck with the DOM problem of having to have everything in memory all at once to satisfy random access?

      It seems to me that the whole argument is more in favour of the XPath language than the whole XSLT. XPath for sure is usefull - it's a very ellegant way of addressing parts of an XML structure. But you can have XPath without XSLT (an example: Template::Plugin::XML::XPath).
Re: Why XSLT and not just Perl?
by Matts (Deacon) on Jun 14, 2003 at 18:57 UTC
    XSLT's advantages really stem from being cross platform. I can take the same XSLT and run it through libxslt, MS-XML, Saxon, Xerces, or any other XSLT engine. That's useful in two ways - it means you can find an optimised XSLT engine for your data (different XSLT engines cope better with different data) and also because it means a lot of people are using XSLT, including non-perl people, so more people can understand the transformation part of your code.

    Another advantage XSLT has over perl is that I've found it to be faster, especially when using libxslt, because it's all happening in C code, rather than Perl.

    Anyhow, if you like Perl for transforming XML you might find XPathScript to be a good best of both worlds. There's a standalone module on CPAN for doing XPathScript transformations, and it's also built into AxKit.

Re: Why XSLT and not just Perl?
by hossman (Prior) on Jun 14, 2003 at 19:03 UTC
    What would a good real world example of why you would use XSLT over Perl?

    When the system you want to render the XML may not have perl.

    Seriously, the power behind XSLT is that it's simple. It's designed to be generic, so that it can be implimented in any number of ways, by any number of systems. You can send a browser an XML file and an XSLT, and trust that the browser can apply it regardless of how that browser was implimented. Or you can use XSLT to generate a report from a bunch of a data, and know that as long as the data format doesn't change, the report format won't change .. even if the reporting systm gets re-implimented by 40 different people.

    Perhaps a better way to explain it is like this...

    XSLT is to language specific templating systems, as XML is to language specific data structures.
    ...You could write an application that saved all of it's data with "use Storable;" and that would be a perfecctly valid design decission if you were 90% confident that no one would ever want to read that data except with a perl program. Or you could use something like XML, and not care what laguage they use. The same is true for XSLT and rendering your data: if you are 90% sure all you ever want is to use perl, then there are probably simpiler ways to do what you want ... or you can use XSLT, and not care what langauge people use to render your data.

Re: Why XSLT and not just Perl?
by webfiend (Vicar) on Jun 14, 2003 at 18:02 UTC

    Text manipulation is one of the tasks that Perl was developed for in the first place. If you already know Perl, then XSLT is going to seem like a poor substitute. I guess the easiest way to put it is along these lines: XSLT wasn't written for you.

    That's an overstatement, of course. It's just that XSLT was written as a XML vocabulary for transforming other XML documents. For an XML author, it has the advantage of familiar syntax. It's also easy to write tools around XSLT (using Perl, for example) to produce a shiny GUI. But if you're only creating them for yourself, you might be happier with Perl.

    The bits of XSLT that I really like involve other tidbits, like XPath. Still learning it, but it's a tremendously convenient notation for building links.

    Besides, there's nothing to stop a clever Perlmonk from embedding Perl code as preprocessor instructions somehow. Then you would get the best of both worlds. Or the worst, depending on your mood that day.

Re: Why XSLT and not just Perl?
by simon.proctor (Vicar) on Jun 14, 2003 at 19:21 UTC
    The core use I have for XSLT at work is when I interface with my Java middleware system using SOAP. The data I get back is encoded in XML and I needed to put these into reasonably complex HTML templates.

    What I didn't do was just do XML->HTML. What I did instead was use XSLT to make a file that Data::Dumper could read and then eval() that.

    I know its a bit perverse but I had a morning to render some data which would have taken me hours to figure out using XPATH.

    With this example in mind, it should indicate that I had data from one system that I needed to translate into another form. Both the data and the translation language followed a set of rules that everyone knows so producing said translation was just a matter of leg work.

    To me that is the power of XSLT. Provided at least one side speaks XML then you can translate into almost anything. In my case, into something that made it easier to use within HTML::Template.

    Of course XSLT (with XPATH et al) is a little verbose and ugly and some of the query statements are profane. But like most other technologies, you use it when its best to and don't when its not.
Re: Why XSLT and not just Perl?
by TomDLux (Vicar) on Jun 14, 2003 at 19:22 UTC

    The reason for using XSLT is that you already have a number of XML tools. The ability to leverage those tools makes XSLT worthwhile.

    Of course, we do have XML tools: it's called Perl. So use Perl to handle your XSLT!

    One thing I find irritating about both XSLT and CSS ( Cascading Style Sheets )---both are concerned with the appearance of documents; both provided less than the full power of a programming language.

    When converting an XML document into HTML, there might be some dynamic text extrtacted from the tags, and some static text. In Perl, the subroutine which processes a tag can generate the static text as well. The two segments are encapsulated into a unit, and distinguinished from the text, static or dynamic, associated with another tag. If you decide to rearrange the HTML, it's simple to do so without modifying the routines that deal with the tags.

    Similarly, it is difficult to use symbolic constants in CSS. My web page stylesheets refer to colours in various places. The first rule of CS club says to use symbolic constants, so that when you decide to change the colours, you find all the instances of the colour. (And also to make sure that if #40f098 is used for two purposes, only the one which is supposed to change gets modified.)


Re: Why XSLT and not just Perl?
by gmpassos (Priest) on Jun 15, 2003 at 07:56 UTC
    Just to point another XML handler for Perl: XML::Smart. (A Java version is comming...) ;-P

    Graciliano M. P.
    "The creativity is the expression of the liberty".

      Of course with a name like this, the OP has no clue why XML::Smart really is smart. :) </nag>

      Makeshifts last the longest.

Re: Why XSLT and not just Perl?
by Willard B. Trophy (Hermit) on Jun 16, 2003 at 21:06 UTC
    You can do client-side XSLT transformation with Mozilla and IE6. All it needs is the web server setup up to correctly identify the mime types.

    It's great for shifting the burden of reporting to the client. Just punt them the XML, pointing to the desired report XSLT, and let their browser get on with it.

    bowling trophy thieves, die!

      Assuming you want to place such a restrictive versioning burdon on your web clients. I'd consider doing this sort of thing on a company intranet, I'd never do this for anything externally facing.

        Never say never...

        Nevermind that, eventually, most browsers will support it... for the ones that don't indicate that they can Accept the right media types, you can always do server side XSLT processing.

        I think Willard B. Trophy hit the nail on the head with his reply.

        "My two cents aren't worth a dime.";

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://265926]
Approved by vek
Front-paged by djantzen
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-14 09:37 GMT
Find Nodes?
    Voting Booth?

    No recent polls found