Skip to main content
XMLDir

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

XPath function

substring()

A slice of a string, indexed from 1 — not from 0, which is the mistake that shifts every result by one character.

substring(s, start, length) returns length characters beginning at position start. Positions are one-based: substring('hello', 1, 2) is 'he'.

Omitting length takes everything to the end. Out-of-range positions are handled by clipping rather than by erroring, which is convenient and hides mistakes.

Syntax
substring(string, start, length?) → string
Returns
string
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.

  • substring('2026-01-01', 1, 4)on order.xmlRun
    2026
  • substring('2026-01-01', 6)on order.xmlRun
    01-01
  • substring('hello', 0, 2)on order.xmlRun
    h

    Zero-based thinking gives one character, not two: positions 0 and 1 are requested, and only 1 exists.

Run your own expression

What catches people out

  • Indexing starts at 1. substring(s, 0, n) returns n-1 characters, silently.
  • The arguments are rounded, so substring(s, 1.5, 2.6) is legal and does something surprising.
  • A start beyond the string returns the empty string rather than an error.

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.