I need to count all b nodes which are not empty (so result should be 2).
<a>
<b>1</b>
<b/>
<b>g</b>
</a>
I'm using code below but this returns count off all nodes (empty included).
select top 1 rc.XmlContent.value('count(//a/b)', 'int') from Table rc
Sorry, this is not the answer! I misread this completely and thought your are looking for the empty nodes. There is an appropriate answer given by GarethD already (same idea, just the other way round).
I don't delete it, because it might help others...
The empty element <b/>
(same as <b></b>
) is existing but has no text()
.
DECLARE @xml XML =
N'<a>
<b>1</b>
<b/>
<b></b>
<b>g</b>
</a>';
select @xml.value('count(/a/b[empty(text())])', 'int')
This returns 2, because there is <b/>
and <b></b>
.
Just for completeness, you might negate the predicate, which is your needed result actually:
select @xml.value('count(/a/b[not(empty(text()))])', 'int')
If you use //a/b/text()
rather than just //a/b
, then you get a count of 2
DECLARE @x XML= '<a><b>1</b><b/><b>g</b></a>';
SELECT @x.value('count(//a/b/text())', 'int');
Use this XPath expression
count(/a/b[normalize-space(text())=''])
Incorporated in your code it would look like this:
select top 1 rc.XmlContent.value('count(/a/b[normalize-space(text())=""])', 'int') from Table rc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.