|
Subject: [xsl] Is XPath and/or XSLT designed such that I should never have to write special case code? From: "Roger L Costello costello@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx> Date: Tue, 22 Jun 2021 17:03:43 -0000 |
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
| Current Thread |
|---|
|
| <- Previous | Index | Next -> |
|---|---|---|
| Re: [xsl] constructing arrays in XS, Michael Kay mike@xxx | Thread | Re: [xsl] Is XPath and/or XSLT desi, Dimitre Novatchev dn |
| Re: [xsl] An XPath expression that , Wendell Piez wapiez@ | Date | Re: [xsl] Is XPath and/or XSLT desi, Eliot Kimber ekimber |
| Month |