PostgreSQL – XPATH Function
The xpath
function in PostgreSQL is used to extract XML nodes from an XML document that match a specified XPath expression. XPath is a query language for XML documents that allows you to navigate and select elements and attributes within the XML structure.
Below is the syntax for the xpath
function:
xpath(xpath_expression, xml)
where xpath_expression
is the XPath expression that defines the criteria for selecting XML nodes within the XML document.
and xml
is the XML document from which you want to extract nodes.
Below is an example of using the xpath
function:
Consider an XML document representing a list of books:
SELECT xpath('//book/title', '<library><book><title>Book 1</title></book><book><title>Book 2</title></book></library>') AS titles;
In this example, the xpath
function is used to extract the <title>
elements from the XML document. The XPath expression //book/title
selects all <title>
elements that are descendants of <book>
elements at any level within the XML document.
The result of this query would be:
{"<title>Book 1</title>", "<title>Book 2</title>"}
The xpath
function returns an array of text values, where each element of the array corresponds to a matching XML node.
You can use various XPath expressions to navigate and select nodes within the XML document. The xpath
function is useful when you need to query and extract information from XML documents stored in your PostgreSQL database or when processing XML data within your SQL queries.