Skip to main content
XMLDir

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

XPath function

string-length()

The number of characters in a string. With no argument, of the context node.

string-length() counts characters, not bytes — an accented letter is one, and so is any character in the Basic Multilingual Plane. With no argument it applies to the string-value of the context node.

It is most often used as an emptiness test: [string-length(x) > 0] is 'x has content'.

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

  • string-length('WIDGET-1')on order.xmlRun
    8
  • string-length(//customer)on order.xmlRun
    12
  • count(//line[string-length(@sku) > 8])on order.xmlRun
    1

    Only GIFT-WRAP is longer than eight characters.

Run your own expression

What catches people out

  • Characters, not bytes. A multi-byte character counts once.
  • On a node-set it uses the first node only, after converting to its string-value.
  • For 'is this element present', prefer count() — an element that exists but is empty has length 0.

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.