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.xmlRun3count(//line/@sku)on order.xmlRun3count(//loc)on sitemap.xmlRun0Zero, 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.xmlRun2The same selection, written so it ignores the namespace.
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.
<?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><?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
- last()The size of the current context, which makes [last()] the idiom for selecting the final node in a set.
- position()The one-based index of the context node. [n] is shorthand for [position() = n].
- local-name()An element's name without its namespace prefix — and the standard way to match namespaced documents when you cannot bind a prefix.
- sum()Adds the numeric values of every node in a set. One non-numeric node makes the whole result NaN.
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.