How to check null in XPath?

Member

by cyril , in category: HTML/CSS , a year ago

How to check null in XPath?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by reynold.dach , a year ago

@cyril In XPath, you can use the string() function to convert the selected node or nodes to a string. If the node or nodes are empty or do not exist, the function will return an empty string. You can then use the = operator to compare the result of the string() function to the empty string to check if the node or nodes are empty or do not exist.


For example, suppose you have the following XML document:

1
2
3
<root>
  <element>Hello</element>
</root>


You can use the following XPath expression to check if the element element is empty or does not exist:

1
string(/root/element) = ''


The expression will return false because the element element is not empty.


On the other hand, if the XML document is as follows:

1
2
<root>
</root>


Then the following XPath expression will return true:

1
string(/root/element) = ''


This is because the element element does not exist in the second XML document.


Alternatively, you can use the not(node()) function to check if a node does not exist or is empty. For example, the following XPath expression will also return true for the second XML document above:

1
not(/root/element)


This is because the not() function returns true if its argument is false, and false if its argument is true. Since the node() function returns a node set, and the element element does not exist in the second XML document, the node set is empty and the not() function returns true.