How to check a node contains empty string or space or null in xpath?
Asked Answered
E

2

5

I want to check using xpath an node in the xml contains empty string/spaces. What is the xpath expression i need to use?

eg:

 <p:insert_acc_data_file xmlns:p="http://ws.wso2.org/dataservice">
<p:Id>123</p:Id>
<p:Name></p:pName>
</p:insert_acc_data_file>

How to check the Name node is empty or containing space values?

Eddo answered 23/5, 2014 at 8:9 Comment(0)
P
8

By checking if a node is empty I guess you mean has no child element (text or node).

Checking if a node contains only space values can be done using normalize-space() function.

I suggest you use this condition: not(./*) and normalize-space(.)="", i.e.

  • does not have child nodes
  • and if it has child text element, the whitespace normalized string representation of the node is an empty string
Pintsize answered 23/5, 2014 at 8:59 Comment(3)
If I am not mistaking * matches elements, but not text nodes. So I think you should use not(./node()) if you want to know your element doesn't have chlid nodes no matter the typeCorotto
@EduardDrenth, I believe you are correct, * will match elements. I think my query is correct for the case of <p:Name> </p:pName> (an element with a text node with only whitespace). My comments is probably wrong here, where "does not have child nodes" should read "does not have child elements"Pintsize
It is also useful to strip &nbsp; characters when looking for whitespace. e.g. '//p[not(./*) and normalize-space(translate(., "", " "))=""]' or '//p[not(./*) and normalize-space(translate(., "&#160;", " "))=""]' (the former is the UTF8 character 0xA0.)Lon
S
0

For both mentioned type.

<Employee/>
<Employee></Employee>

Below code will work

string(your_node_xpath) != ''
Strangulate answered 29/5, 2020 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.