Skip to main content
XMLDir

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

XPath function

contains()

Whether one string occurs inside another. The most-used XPath function, and the one most often given its arguments the wrong way round.

contains(a, b) is true when b appears anywhere in a. Argument order is haystack first, needle second — the opposite of what several other languages do, and the reason a working expression suddenly matches nothing.

It is a substring test, not a pattern match. There is no regular expression support in XPath 1.0 at all: matches() is XPath 2.0 and will report as an unregistered function here.

Syntax
contains(haystack, needle) → boolean
Returns
boolean
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[contains(@sku, 'WIDGET')])on order.xmlRun
    2
  • //line[contains(@sku, 'GIFT')]/@skuon order.xmlRun
     sku="GIFT-WRAP"
  • contains('WIDGET-1', 'WIDGET')on order.xmlRun
    true
  • contains('WIDGET', 'WIDGET-1')on order.xmlRun
    false

    The same two strings, swapped. This is the mistake.

Run your own expression

What catches people out

  • Haystack first, needle second. contains(@sku, 'WIDGET') — not contains('WIDGET', @sku).
  • It is case-sensitive, and XPath 1.0 has no lower-case(). Use translate() to fold case.
  • Given a node-set, only the first node in document order is converted to a string — the rest are ignored silently.
  • contains(x, '') is true for every x, so an empty search term matches everything.

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.