Skip to main content
XMLDir

Search 169 pages — formats, namespaces, parser messages, schema errors and tools.

XPath function

count()

How many nodes a node-set contains. The fastest way to check whether an expression matches what you think it does.

count() takes a node-set and returns its size. It is the first thing to reach for when an expression is not doing what you expect: wrap it in count() and you learn immediately whether the problem is the selection or what you are doing with it.

It counts nodes, not values. count(//line/@sku) is three because there are three attribute nodes, even if two of them held the same string.

Syntax
count(node-set) → number
Returns
number
Kind
Function
Version
XPath 1.0 (libxml2)

Worked examples

Each result below is what the evaluator returned, asserted on every test run. An empty result means an empty node-set — which is an answer, not an error.

  • count(//line)on order.xmlRun
    3
  • count(//line/@sku)on order.xmlRun
    3
  • count(//loc)on sitemap.xmlRun
    0

    Zero, not two. The document has a default namespace, and an unprefixed name in XPath 1.0 means 'no namespace'.

  • count(//*[local-name()='loc'])on sitemap.xmlRun
    2

    The same selection, written so it ignores the namespace.

Run your own expression

What catches people out

  • count() of an empty node-set is 0, not an error — so `count(//nope) = 0` is true rather than a failure.
  • Passing a string or number is an error, not a coercion: count('abc') will not compile.
  • In a namespaced document, count() is how you discover that your path matches nothing at all.

The sample documents

Every example on this page runs against these documents. The sitemap one is namespaced on purpose — almost every real XML document is, and that changes which expressions match.

order.xml
<?xml version="1.0" encoding="UTF-8"?>
<order id="A-1001" tier="gold">
  <customer country="NO">Ada Lovelace</customer>
  <lines>
    <line sku="WIDGET-1" qty="2"><price>14.50</price></line>
    <line sku="WIDGET-2" qty="1"><price>39.00</price></line>
    <line sku="GIFT-WRAP" qty="1"><price>0.00</price></line>
  </lines>
  <note>  Deliver after 09:00  </note>
</order>
sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>https://example.com/</loc><lastmod>2026-01-01</lastmod></url>
  <url><loc>https://example.com/pricing</loc></url>
</urlset>

Related

All 34 XPath entries

Get started

Bring order to the XML your team can't afford to ignore.

Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.