Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xslt

xpath

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?

like image 445
Johan Avatar asked Oct 03 '10 22:10

Johan


People also ask

How do I select the last child in xpath?

"last() method" selects the last element (of mentioned type) out of all input element present.

What is lastChild in javascript?

The read-only lastChild property of the Node interface returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child nodes.


1 Answers

Just select the last node of the <foo> element and then use self axis to resolve the node type.

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

This XPath expression returns an empty set (which equates to boolean false) if the last node is not an element. If you want to specifically get value true or false, wrap this expression in the XPath function boolean(). Use self::* instead of self::bar to match any element as the last node.

Input XML document:

<root>
    <foo>some text <bar/> and maybe some more</foo>
    <foo>some text <bar/> and a last <bar/></foo>
</root>

XSLT document example:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text"/>

<xsl:template match="foo">
    <xsl:choose>
        <xsl:when test="node()[position()=last()]/self::bar">
            <xsl:text>bar element at the end&#10;</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>text at the end&#10;</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Output of the stylesheet:

text at the end
bar element at the end
like image 192
jasso Avatar answered Sep 28 '22 04:09

jasso