Say I have a pair of XML documents
<Foo>
<Bar/>
<Baz>mystring</Baz>
</Foo>
and
<Foo>
<Bar/>
</Foo>
I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried
(string('not-found') | //Baz)[last()]
but the left hand side of the union isn't a node-set
Special case: If you want to get 0 if numeric node is missing or empty, use "sum(/Foo/Baz)" function
In XPath 1.0, use:
If you want to handle the posible empty
Baz
element, use:With this input:
Result:
not-found
string data type.@Alejandro provided the best XPath 1.0 answer, which has been known for years, since first used by Jeni Tennison almost ten years ago.
The only problem with this expression is its shiny elegance, which makes it difficult to understand by not only novice programmers.
In a hosted XPath 1.0 (and every XPath is hosted!) one can use more understandable expressions:
Here the variable
$vDefaults
is a separate document that has the same structure as the primary XML document, and whose text nodes contain default values.Or, if XSLT is the hosting language, one can use the
document()
function:Or, not using
concat()
:If you are okay with printing an empty string instead of 'not-found' message then use:
Later, you can replace the empty strings with 'not-found'.