Skip to main content
XMLDir

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

XPath function

string()

Converts anything to a string — and for a node-set, takes only the first node in document order.

string() converts its argument using XPath's conversion rules: a number becomes its decimal form, a boolean becomes 'true' or 'false', and a node-set becomes the string-value of its first node in document order.

That last rule is the one that surprises people. string(//line/@sku) is not all three SKUs — it is the first, silently.

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

  • string(/order/@id)on order.xmlRun
    A-1001
  • string(//line/@sku)on order.xmlRun
    WIDGET-1

    Three attributes match; only the first becomes the string.

  • string(1 = 1)on order.xmlRun
    true

Run your own expression

What catches people out

  • On a node-set it uses the first node only. To get every value, select the node-set itself rather than converting it.
  • string() of an empty node-set is the empty string, not an error.
  • The string-value of an element is the concatenation of all descendant text, indentation included — see normalize-space().

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.