Re: [xsl] Checking if a variable has a value

Subject: Re: [xsl] Checking if a variable has a value
From: "Graydon graydon@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Wed, 31 Aug 2022 01:44:20 -0000
On Wed, Aug 31, 2022 at 01:27:20AM -0000, Mark Giffin m1879@xxxxxxxxxxxxx scripsit:
> XSLT 2.0, Saxon processor.
> 
> What's a good way to check if a variable has a value? 

> I tried this and others:
> <xsl:if test="matches($git-hash, '\d|[a-z]')">
>     <dc:subject>git hash: <xsl:value-of select="$git-hash"/></dc:subject>    
> </xsl:if>

<xsl:if test="normalize-space($git-hash)">
    <dc:subject>git hash: <xsl:value-of select="$git-hash"/></dc:subject>
</xsl:if>

would be customary.

string-length($git-hash)

(since 0 is false)

matches($git-hash,'\P{Zs}')

("any character EXCEPT a member of the unicode character category "Separator, space")

exists($git-hash)

returns true if the sequence isn't empty, and a variable with one thing
in it is a sequence of length one.

Would also all work.

(So would head($git-hash) but I don't think fn:head() is available in
2.)

I would generally want to go with exists(), at least if you're sure
you're getting actual nothing in the param when you're not getting the
hash value. Typing parameters is generally helpful with avoiding that
kind of surprise but not so much when it might be one space instead of
the expected hash value, since they'd both be strings.  (Type the param
anyway, just in case.)

-- 
Graydon Saunders  | graydonish@xxxxxxxxx
^fs oferiode, pisses swa mfg.
-- Deor  ("That passed, so may this.")

Current Thread