Re: [xsl] How to test with XPath the existence of a certain branch of a <choice> statement?

Subject: Re: [xsl] How to test with XPath the existence of a certain branch of a <choice> statement?
From: Abel Braaksma <>
Date: Wed, 03 Feb 2010 21:09:45 +0100
Hi Ben,

Normally, when doing XSLT transformations, you'd let the processor decide for you. If you, for instance, do the following:

<xsl:apply-templates select="parent/choice/sequence" />

it will process all sequences which can be "caught" (handled) by your templates:

   <xsl:template match="sequence">

Now, in the above situation, you can test for the presence of children in several ways. Suppose you want to do something special with empty <sequence> nodes and something with filled <sequence> nodes. Then you can solve that as follows:

   <!-- catches all filled sequence nodes -->
   <xsl:template match="sequence[*]">
     <xsl:text>found a filled sequence!</xsl:text>

   <!-- catches the rest, i.e., empty nodes (or nodes with only text) -->
   <xsl:template match="sequence">
     <xsl:text>found an empty one!</xsl:text>

The same test you can also apply in an xsl:if:

   <!-- contains at least an element -->
   <xsl:if test="sequence[*]">....</

   <!-- contains element <aaaa> -->
   <xsl:if test="sequence[aaaa]">....</

   <!-- contains any node, even a text node or comment node -->
   <xsl:if test="sequence[node()]">....</

   <!-- any sequence -->
   <xsl:if test="sequence">....</

Here you immediately see the problem with xsl:if, if you have to adjust for all case, you need to inverse your logic. In this case, testing for emptiness can be done as follows

   <!-- empty sequence element -->
   <xsl:if test="sequence[not(*)]">....</

Kind regards,

Abel Braaksma

Ben Stover wrote:
For an XSLT script I need to check wether one certain branch of a <choice> statement is present.
The critical part of the XML statement look like as follows (<choice> and <sequence> are taken/inserted from the underlying XSD schema file):


As you can see a XML doc can contain one of the three sequence branches.

How do I check with XPath if the first branch is currently filled in an XML doc?

If I code e.g.


then it is not clear if the first or second branch is present.

Can anyone give me a hint?

Thank you

Current Thread