xsl-list
[Top] [All Lists]

[xsl] Is XPath and/or XSLT designed such that I should never have to write special case code?

2021-06-22 12:03:51
Hi Folks,

I think special case code is evil. 

To explain what I mean by "special case code" let's take its opposite: code 
selects what is desired under any condition. 

So, by "special case code" I mean extra code that is written for dealing with 
special conditions. 

Last week I posted the following XPath expression to fetch the <Row> element 
where Cell[1]/Data equals $element and Cell[2]/Data equals $parent.

$document/Row[Cell[1]/Data eq $element][Cell[2]/Data eq $parent]

However, when $parent is empty, the XPath expression fails. 

I was all set to write special case code:

<xsl:if test="empty(Cell[2]/Data)"> do something </xsl:if>

Bad, bad, bad.

But then Mukul showed me an XPath expression that works correctly -- whether 
$parent is empty or not -- without any special case code:

$document/Row[Cell[1]/Data eq $element][Cell[2]/string(Data) eq $parent]

Awesome!

Today I was writing some XSLT to generate a bunch of rows showing, for each 
element in an XML document, its name, the name of its parent, the name of its 
grandparent, and the name of its great-grandparent:

<xsl:template match="*">
    <row>
        <element><xsl:value-of select="name(.)"/></element>
        <parent-element><xsl:value-of select="name(..)"/></parent-element>
        <grandparent-element><xsl:value-of 
select="name(../../..)"/></grandparent-element>
        <great-grandparent-element><xsl:value-of 
select="name(../../../..)"/></great-grandparent-element>
    </row>
    <xsl:apply-templates select="*" />
</xsl:template>

Obviously as the XSLT traverses through an XML document some elements don't 
have a great-grandparent or a grandparent or even a parent. But I didn't need 
to write special case code to check those conditions. That is terrific!

Question #1: is XPath and/or XSLT designed such that I should never have to 
write special case code? 

Question #2: If I find myself writing special case code, should I stop and say, 
"How can I modify this XPath and/or XSLT so that I do not have to write special 
case code?

/Roger
--~----------------------------------------------------------------
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
EasyUnsubscribe: http://lists.mulberrytech.com/unsub/xsl-list/1167547
or by email: xsl-list-unsub(_at_)lists(_dot_)mulberrytech(_dot_)com
--~--


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