Forum Moderators: open

Message Too Old, No Replies

Testing for an attribute using XPath

attribute existence xpath

         

Joshie76returns

11:46 am on Jan 22, 2005 (gmt 0)

10+ Year Member



Are the following valid, correct and reliable ways of testing for the existence of an attribute on the context node...

Example 1: Only match nodes that have the example attribute...

<xsl:for-each "sample[@example]">
</xsl:for-each>

Example 2: Use an if statement to decide whether to perform an action based on the existence (irrelevant of content) of the example attribute on the current context node...

<xsl:if test="@example">
</xsl:if>

I have always used this technique in the past but I overheard someone say it was incorrect - I'm trying to work out why....

choster

4:45 pm on Jan 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



1) To match child nodes with the "example" attribute, you want to use

<xsl:for-each [b]select=[/b]"sample[@example]">
...
</xsl:for-each>

2) I think it is technically more correct to use

<xsl:if test="boolean(@example)">
...
</xsl:if>

to test for the existence of the "example" attribute.

Joshie76returns

7:58 pm on Jan 24, 2005 (gmt 0)

10+ Year Member



But wouldn't that test the value of the attribute and not the existence of the node?

See [msdn.microsoft.com...]

PS - Whoops, thanks for spotting the missing select=

choster

7:50 pm on Jan 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, if you pass an XPath to
boolean
it will first test for (non-)existence, plus the result (true/false) is predictable across processors. Based on the following references it would seem processors which accept a direct
<xsl:if test="@example">
are implicitly testing boolean(@example).

[dpawson.co.uk...]
[msdn.microsoft.com...]

Joshie76returns

9:17 pm on Jan 26, 2005 (gmt 0)

10+ Year Member



but it also says that non-empty strings evaluate to true - so wouldn't the following...

<sample example=""/>

<xsl:if test="boolean(@example)">

... evaluate to false?