XPath 3.1 Data Types

XPath selects nodes from XML and computes values from them. It is the expression language inside XSLT, XQuery, XSD assertions, Schematron and XPointer. XPath 1.0 (1999) knew four types; versions 2.0 (2007) and 3.0 (2014) rebuilt it on XML Schema's types, and XPath 3.1 (21 March 2017), the current Recommendation, added maps, arrays and JSON. To try expressions quickly, a third wrapper, xp, prints each argument beside its result (or its error code), evaluated against booknest-catalog.xml or the file in XP_DOC; multi-line results are joined into one line. Sections 2.5 to XPath Core Functions use it throughout:

xp: evaluate several XPath expressions and print each with its resultShell
cat > ~/bin/xp <<'EOF'
#!/bin/sh
# xp EXPR...: evaluate XPath expressions against $XP_DOC (default booknest-catalog.xml)
err=$(mktemp)
for e in "$@"; do
  if r=$(xquery -s:"${XP_DOC:-booknest-catalog.xml}" -qs:"$e" 2>"$err"); then
    r=$(printf '%s\n' "$r" | paste -sd ' ')
  else
    r="error $(grep -oE '[A-Z]{4}[0-9]{4}' "$err" | grep -v '^SXW' | head -n 1)"
  fi
  printf '%-38s => %s\n' "$e" "$r"
done
rm -f "$err"
EOF
chmod +x ~/bin/xp

Subsections


XPath

XPath is a language for selecting nodes from an XML document. It can also be used to compute values in the context of an XML document.

XPath is used in XPointer, XInclude, XSD, Schematron, XQuery, XSLT, and XForms. XPath can be evaluated in GUI tools such as XML ValidatorBuddy and online tools such as https://www.videlibri.de/cgi-bin/xidelcgi.

XPath 3.1 (21 Mar 2017) is the last version published as a full W3C Recommendation. It adds support for arrays, maps, and arrow-chaining (=>) of functions. XPath 4.0 is under active development by the W3C's QT4CG (XQuery and XSLT 4.0 Community Group) as a series of Community Group drafts; it is not yet a W3C Recommendation and its details are still evolving. XPath 4.0 is a superset of 3.1, adding native JSON support (rather than only XML) and many new functions.

This section covers:
ch03-xpath-overview.xmlXML
<?xml version="1.0"?>
<menu restaurant="Golden Outlet">
   <dish id="1">Satay <i>Cooked</i></dish>
   <drink id="2">Cola</drink>
   <dish id="3">Curry Chicken</dish>
</menu>

<!-- Example XPath expressions against the document above -->
<!-- //dish            selects all <dish> nodes anywhere in the document -->
<!-- /menu/@restaurant  selects the restaurant attribute of the root element -->