Home > Blockchain >  XPath/XSLT select only where count is less than number
XPath/XSLT select only where count is less than number

Time:04-20

Given the structure below. How would you go about selecting only those elements where the number of elements of same group is less than - let's say six. In this sample it would mean we'll only select data in group B, C, E and F.

I have played with distinct-values and this:

//distinct-values(data/@group) gives me the list of distinct values in the xml, but trying to combine the output with count and others - ends up giving me the number 31 which is the total number of elements.

Any pointers are welcome

<datas>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="A">A</data>
    <data group="B">B</data>
    <data group="B">B</data>
    <data group="B">B</data>
    <data group="B">B</data>
    <data group="C">C</data>
    <data group="C">C</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="D">D</data>
    <data group="E">E</data>
    <data group="E">E</data>
    <data group="E">E</data>
    <data group="E">E</data>
    <data group="F">F</data>
    <data group="F">F</data>
</datas>

CodePudding user response:

After more research I found a solution which seems to work.

for $d in //distinct-values(data/@group) return //data[@group=$d and count(//data[@group=$d]) <= 7]

Does anyone agree this is a valid solution?

CodePudding user response:

Depending on what you are doing with your data and seeing you tagged your question as XSLT, something like this could also be useful :

<xsl:for-each-group select="datas/data" group-by="@group">
   <xsl:if test="count(current-group()) lt 6">
     <group><xsl:value-of select="current-grouping-key()"/></group>
   </xsl:if>
</xsl:for-each-group>
  • Related