xsl-list
[Top] [All Lists]

RE: [xsl] Counting indent level

2008-09-29 04:17:01
This entire xslt file is pretty simple, it's basically just 
that one for each and produces a single list of elements.  Is 
there any other advantages (other than easier maintenance) to 
use templates over the for-each?

Well, the obvious advantage is that Ken's code works, and yours doesn't.

But let's try and remember the reasons for this advice that we always give
to beginners. In a case like this, where the input is a recursive structure,
the use of apply-templates is so instinctive to an experienced user that
it's quite difficult to explain the reasons - it's like trying to explain
why we swing our arms when we walk.

There are cases where it actually doesn't make much difference. Those are
cases where the input structure is very regular and has different data at
each level, with no recursion. In those cases xsl:for-each works quite
acceptably well. But where the input structure is recursive, where the same
element can appear at different levels, or where many different elements can
appear at any point in the structure, the advantages of the recursive
descent pattern using apply-templates are overwhelming.

The benefits come from two main sources.

Firstly, your processing structure is aligned to the input data structure.
That's always a good principle to follow in program design. It makes it much
easier to follow the logic.

Secondly, the logic decouples "how to process an element" from "what
elements can appear here". This is particularly useful when elements can
appear in more than one place, as it leads to better reusability of code, as
well as robustness in the face of schema change.

The problem as you expressed it "The reason for that is that a item node
might also contain child nodes that are also called <item> nodes that I
don't want.  I only want a item node that has it's immediate parent a group
node." hits the nail on the head. The for-each style of logic is clumsy when
you are trying to implement rules like this. Rule-based processing by
contrast gives a very close match between the code you write and your
English-language description of the problem.

Michael Kay
http://www.saxonica.com/


--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>