I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.
Is that possible?
Unlike ID attributes, every element in a web page has a unique XPath.
Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition.
XPath (XML Path Language) is an expression language designed to support the query or transformation of XML documents. It was defined by the World Wide Web Consortium (W3C) and can be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document.
It can be done but only if the return value when the node does exist is the string value of the node, not the node itself. The XPath
substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz)))
will return the string value of the baz
element if it exists, otherwise the string "N/A".
To generalize the approach:
substring(concat($null-value, $node),
(string-length($null-value) + 1) * number(boolean($node)))
where $null-value
is the null value string and $node
the expression to select the node. Note that if $node
evaluates to a node-set that contains more than one node, the string value of the first node is used.
Short answer: no. Such a function was considered and explicitly rejected for version 2 of the XPath spec (see the non-normative Illustrative User-written Functions section).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With