Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a value for a missing tag in XPath?

Tags:

xml

xslt

xpath

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?

like image 875
JPLemme Avatar asked Sep 02 '08 19:09

JPLemme


People also ask

Is XPath unique for each element?

Unlike ID attributes, every element in a web page has a unique XPath.

What is XPath predicate?

Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition.

What is XPath value?

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.


2 Answers

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.

like image 50
jelovirt Avatar answered Nov 15 '22 22:11

jelovirt


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).

like image 42
Hank Gay Avatar answered Nov 15 '22 22:11

Hank Gay