XSLT, XPath unique child nodes only problem where non unique nodes are not selected at all -
<root> <parent> <child> <name>john</name> </child> <child> <name>ben</name> </child> </parent> <parent> <child> <name>john</name> </child> <child> <name>mark</name> </child> <child> <name>luke</name> </child> </parent> </root>
i want unique child nodes i.e. 1 child node if there more 1 same name.
such as:
john ben mark luke
i have tried:
<xsl:for-each select="parent"> <xsl:for-each select="child[name != preceding::name]"> <xsl:value-of select="name"/> </xsl:for-each> </xsl:for-each>
but get:
ben mark luke
?!
your problem using !=
operator comparison between value , node-set.
this wrong -- avoid using !=
operator , use not()
function , =
operator when 1 of operands in comparison node-set.
below correct solution:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/*"> <xsl:for-each select="parent"> <xsl:for-each select="child[not(name = preceding::name)]"> <xsl:value-of select="concat(name, ' ')"/> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet>
when transformation applied on provided xml document:
<root> <parent> <child> <name>john</name> </child> <child> <name>ben</name> </child> </parent> <parent> <child> <name>john</name> </child> <child> <name>mark</name> </child> <child> <name>luke</name> </child> </parent> </root>
the wanted, correct result produced:
john ben mark luke
explanation: here how w3c xpath 1.0 spec defines semantics of !=
operator:
"if 1 object compared node-set , other string, comparison true if , if there node in node-set such result of performing comparison on string-value of node , other string true."
this means
's' != node-set
is true if there 1 node in node-set
isn't equal 's'
.
this isn't semantics wanted.
on other side,
not('s' = node-set())
is true only if there isn't node in node-set
equal 's'
.
this wanted comparison.
do note: grouping technique have chosen o(n^2) , should used on small sets of values dedupped. if efficiency needed, means use muenchian method grouping (discussing or demo-ing falls outside scope of question).
Comments
Post a Comment