Skip to main content
XMLDir

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

XPath function

normalize-space()

Trims leading and trailing whitespace and collapses internal runs to single spaces — the fix for text that looks equal and is not.

XML preserves the whitespace an author used for indentation, so an element's text-value routinely carries newlines and leading spaces that nobody intended as content. normalize-space() removes them: it trims both ends and collapses every internal run of whitespace to one space.

This is why a comparison that looks obviously true returns false. //note = 'Deliver after 09:00' fails when the source is indented; normalize-space(//note) = 'Deliver after 09:00' succeeds.

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

  • normalize-space(//note)on order.xmlRun
    Deliver after 09:00
  • //note = 'Deliver after 09:00'on order.xmlRun
    false

    False, because the element's value has the source indentation still attached.

  • normalize-space(//note) = 'Deliver after 09:00'on order.xmlRun
    true

Run your own expression

What catches people out

  • This is the first thing to try when a string comparison that should be true is false.
  • It collapses internal whitespace too, so it is not a trim — a value with meaningful double spaces will be changed.
  • With no argument it applies to the context node, which inside a predicate is usually what you want.

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.