Alex Rivera | Logout

XSLT, finding out if last child node is a specific element

Asked 2010-10-03T22:17:19.420
9

Look at the following two examples:

<foo>some text <bar/> and maybe some more</foo>

and

<foo>some text <bar/> and a last <bar/></foo>

Mixed text nodes and bar elements within the foo element. Now I am in foo, and want to find out if the last child is a bar. The first example should prove false, as there are text after the bar, but the second example should be true.

How can I accomplish this with XSLT?

Edit
Report

1 Answer

7

Now I am in foo, and want to find out if the last child is a bar

Use:

node()[last()][self::bar]

The boolean value of any non-empty node-set is true() and it is false() for otherwise. You can use the above expression directly (unmodified) as the value of the test attribute of any <xsl:if> or <xsl:when>.

Better, use:

foo/node()[last()][self::bar]

as the match attribute of an <xsl:template> -- thus you write in pure "push" style.

answered 2010-10-04T00:14:51.317

Your Answer