XPath filter not empty child element
Solution 1
Since FileName
is a child element and not an attribute, you need to access it as such and not use the attribute qualifier @
in front of the node name.
Try:
<xsl:template match="DocumentElement/QueryResults[FileName]">
This will select the DocumentElement/QueryResults
elements that have a FileName
child element.
If, however, you always have a FileName
child element (sometimes empty) and you want to select the non empty ones, try this:
<xsl:template match="DocumentElement/QueryResults[string-length(FileName) > 0]">
Solution 2
<xsl:template match="DocumentElement/QueryResults[FileName != '']">
That's just a quick guess, and I haven't worked with XPath/XSLT in a long time. Still, if it's empty, then that should skip over it. While I prefer to use the functions like string-length
, not all UAs support them (notably client-side XSLT parsers that barely work with XPath and XSLT 1.0 at all, nevermind the useful functions and functionality that XSLT 2.0 and XPath provide).
Marcos Buarque
Journalist, musician, developer and web project manager based in Rio de Janeiro, Brazil. Marcos is the owner of SPEL, a virtual agency that develops web projects and solutions for customers all over the world.
Updated on June 15, 2022Comments
-
Marcos Buarque about 2 years
I need to filter a XPath expression to grab only a certain attribute as not empty.
I tried this:
<xsl:template match="DocumentElement/QueryResults[string(@FileName)]">
and this:
<xsl:template match="DocumentElement/QueryResults[string-length(@FileName)>0]">
but it did not work. I need the same kind of data returning from the folloing XPath expression...
<xsl:template match="DocumentElement/QueryResults">
... but filtered to avoid items with empty attribute @FileName.
Thanks!