I need to check if an XML node has at least one non-empty child. Applied to this XML the expression should return true
<xml>
<node>
<node1/>
<node2/>
<node3>value</node3>
</node>
</xml>
I tried to use this expression: <xsl:if test="not(/xml/node/child::* = '')">
but it seems to check if all children are not empty.
How can I write an expression which returns true
if at least one element is not empty? Is there a way to do this without creating another template to iterate over node chldren?
UPD: I'm thinking of counting non-empty nodes like
test="count(not(/xml/node/child::* = '')) > '0'"
but somehow just can't make it work right. This expression is not a well-formed one.
You just need
<xsl:if test="/xml/node/* != ''" />
.In XPath an
=
or!=
comparison where one side is a node set and the other side is a string succeeds if any of the nodes in the set passes the comparison. Thusmeans "it is not the case that any
x
child element of the current node has an empty string value", which is fundamentally different fromwhich means "at least one
x
child element of the current node has a string value that is not empty". In particular, if you want to check that allx
children are empty, you need to use a "double-negative" testMore accurate, simpler and more efficient (no need to use the
count()
function):If you want to exclude any element that has only whitespace-only text children, use:
Here's one XPath that should accomplish the job:
When used in a sample XSLT:
...which is, in turn, applied to the provided example XML:
...the expected result is produced:
If we apply the same XSLT against a simply modified XML:
...again, the expected result is produced:
Explanation:
The XPath used searches for all children of a
<node>
element (which are, in turn, children of the root element) that have a non-empty text value (as specified bytext()
); should the count of such<node>
children be greater than 0, then the XPath resolves totrue
.Explanation This will find the first node with a string length greater than zero and then compares such node contents with empty string (the comparison will return the existence of a non-empty string node); this code can also be used to look for a specific criteria in any node, for example identify the existence of a node which contains specific string or starts with some character or any other condition; please use this as the inner condition of the node reference for the code to work its magic.