xpath()

Extracts nodes matching an XPath expression from an XML string and returns them.

Syntax

xpath(XML_EXPR, PATH_EXPR)

Parameters

XML_EXPR
The XML string or expression to parse.
PATH_EXPR
An XPath expression string specifying the target to extract.

Description

The xpath() function parses XML_EXPR as an XML document and queries nodes using PATH_EXPR. If any argument is null, returns null. If XML parsing or XPath evaluation fails, also returns null.

If exactly one node matches, the node's value is returned as a single value. If two or more nodes match, their values are returned as a list in order.

Error codes

N/A

Usage examples

  1. Extracting a single node

    json "{'xml': '<root><name>alice</name></root>'}" | eval result = xpath(xml, "/root/name")
    | # result: "alice"
    
  2. Extracting multiple nodes

    json "{'xml': '<root><item>a</item><item>b</item></root>'}" | eval result = xpath(xml, "/root/item")
    | # result: ["a","b"]
    
  3. NULL input

    json "{'xml': null}" | eval result = xpath(xml, "/root/name")
    | # result: null
    

Compatibility

The xpath() function has been available since before Sonar 4.0.