Sponsored

XSLT Reference

has-children()

XSLT 3.0 node function

Returns true if the node has one or more child nodes; defaults to the context node if no argument is supplied.

Syntax
has-children(node?)

Description

has-children() tests whether a node has at least one child node. A child node may be an element, text node, comment, or processing instruction. Attribute nodes and namespace nodes are not children in the XPath data model, so their presence alone does not cause has-children() to return true.

When called without arguments, the function tests the context node. When a node is supplied as an argument, that node is tested. If the argument is the empty sequence, false is returned.

The function is particularly useful in streaming mode where examining all children of a node is expensive or impossible after the streaming pass. has-children() can be evaluated during streaming as a simple flag before the children are consumed.

Parameters

ParameterTypeRequiredDescription
nodenode()?NoThe node to test. Defaults to the context node if omitted.

Return value

xs:booleantrue if the node has one or more child nodes, false otherwise.

Examples

Distinguishing leaf and branch elements

Input XML:

<?xml version="1.0" encoding="UTF-8"?>
<tree>
  <branch>
    <leaf>A</leaf>
    <leaf>B</leaf>
  </branch>
  <leaf>C</leaf>
</tree>

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/tree">
    <classified>
      <xsl:for-each select="*">
        <node name="{name()}" type="{if (has-children()) then 'branch' else 'leaf'}"/>
      </xsl:for-each>
    </classified>
  </xsl:template>
</xsl:stylesheet>

Output:

<classified>
  <node name="branch" type="branch"/>
  <node name="leaf" type="leaf"/>
</classified>

Using has-children() with a supplied node

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>

  <xsl:template match="/tree">
    <xsl:value-of select="has-children(branch)"/>
    <xsl:text>&#10;</xsl:text>
    <xsl:value-of select="has-children(leaf)"/>
  </xsl:template>
</xsl:stylesheet>

Output:

true
false

Notes

  • has-children() is equivalent to exists(child::node()) but may be more efficient when the processor does not need to materialize the child sequence.
  • In streaming mode (xsl:stream), has-children() is one of the few node tests that can be applied without consuming the children.
  • Attribute nodes never have children in the XPath data model, so has-children(@attr) always returns false.
  • Document nodes may also be tested; a document with at least one child element returns true.

See also