Tran Ngu Dang
Tran Ngu Dang

Reputation: 2630

xsl:if at least one child node exists

<node>
   <node1><node11/></node1>
   <node2/>
</node>

I want my XSLT to check

<xsl:if test="If at least 1 child node exists">
  Only node1 can pass the if condition
</xsl:if>

Thanks for any reply.

Upvotes: 20

Views: 44759

Answers (4)

Tim C
Tim C

Reputation: 70618

Firstly, be careful with your terminology here. Do you mean "node" or do you mean "element". A node can be an element, comment, text or processing-instruction.

Anyway, if you do mean element here, to check at least one child element exists, you can just do this (assuming you are positioned on the node element in this case.

<xsl:if test="*">

Your comment suggests only "node1" can pass the if condition, so to check the existence of a specific element, do this

<xsl:if test="node1">

Upvotes: 33

JLRishe
JLRishe

Reputation: 101672

In the context of the node you are testing, this should work to test whether a node has child elements:

<xsl:if test="*">
  Only node1 can pass the if condition
</xsl:if>

If you actually meant nodes (which would include text nodes), then this would work to include text nodes:

<xsl:if test="node()">
  Only node1 can pass the if condition
</xsl:if>

But <node> would also pass this test (<node2> wouldn't). I assumed you were only speaking in the context of <node>'s child nodes, but perhaps not?

Upvotes: 10

David Carlisle
David Carlisle

Reputation: 5652

The wording of the question is unclear but I think you just want to process child nodes that have themselves got children (ie grandchildren of the current node)

<xsl:template match="node">
 do stuff for node
  <xsl:apply-templates select="*[*]"/>
</xsl:template>

will just apply templates to node1 as it has a child node, it will not apply templates to node2.

Upvotes: 0

Paul Butcher
Paul Butcher

Reputation: 6956

Expressions that match a node are truthy, whilst expressions that don't match anything are falsy, so:

<xsl:if test="node()">
   ...
</xsl:if>

However, your question and the implied condition "Only node1 can pass the if condition" are at odds with the example. Both node and node1 have child nodes, so both would pass this if condition.

To limit it strictly to node1, you have to either ensure that the template context is appropriate, or check that the node in question is not the documentElement.

Upvotes: 0

Related Questions