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.
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.
<?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
- starts-with()Whether a string begins with another. XPath 1.0 has no ends-with() — that is 2.0.
- substring-before()Everything before the first occurrence of a marker — and the empty string when the marker is absent, which is not an error you will notice.
- translate()Character-by-character replacement, and the only way to fold case in XPath 1.0 — because lower-case() is 2.0.
- boolean() and not()Converts to true or false. A node-set is true when it is non-empty — which is why [not(x)] means 'has no x'.
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.