Skip to main content
XMLDir

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

XPath function

id()

Selects elements by their DTD-declared ID — which means it does nothing at all in most documents.

id() looks up elements whose ID-typed attribute matches the argument. The catch is what makes an attribute ID-typed: it must be declared so in a DTD, and the DTD must have been read. An attribute merely named 'id' is not an ID.

Because most modern documents carry no DTD, id() usually returns nothing. //*[@id='x'] is what people actually want, and it works everywhere.

Syntax
id(object) → node-set
Returns
node-set
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(id('A-1001'))on order.xmlRun
    0

    Zero despite the document having id="A-1001": no DTD declares that attribute as an ID.

  • count(//*[@id='A-1001'])on order.xmlRun
    1

    What people mean by id(), and what works without a DTD.

Run your own expression

What catches people out

  • An attribute called 'id' is not an ID. Only a DTD (or schema, depending on the processor) can make it one.
  • Most XPath tools do not load external DTDs by default, so id() silently returns an empty node-set rather than telling you why.
  • Use //*[@id='…'] unless you are genuinely working with a DTD-validated document.

The sample documents

Every example on this page runs against this document. 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>

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.