4

I have a question about the use of group-adjacent.

I have seen two patterns being used:

Pattern 1:

<xsl:for-each-group select="*" group-adjacent="boolean(self::p[@class = 'code'])">

Pattern 2:

<xsl:for-each-group select="*" group-adjacent="@class">

Based on what is used, I noticed that current-grouping-key() returns a false.

What is the purpose of using a boolean function in group-adjancent ?

lfurini
  • 3,729
  • 4
  • 30
  • 48

2 Answers2

5

With the form <xsl:for-each-group select="*" group-adjacent="boolean(self::p[@class = 'code'])"> the grouping key is a boolean value that is true for adjacent p elements having the class attribute with value code while with the second form <xsl:for-each-group select="*" group-adjacent="@class"> the grouping value is a string and groups all adjacent elements with the same class attribute values.

So it depends on your needs, if you have e.g.

<items>
  <item class="c1">...</item>
  <item class="c1">...</item>
  <item class="c2">...</item>
</items>

you can use the second approach to group on the class value.

On the other hand, if you want to identify adjacent p elements with a certain class attribute, as e.g. in

<body>
  <h1>...</h1>
  <p class="code">...</p>
  <p class="code">...</p>
  <h2>...</h2>
  <p class="code">...</p>
</body>

then the first approach allows that.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • Very helpful. Thank you for responding. This certainly helps me understand the code rather than blindly following a solution posted. – StillStumbling Apr 22 '15 at 20:28
2

Based on what is used, I noticed that current-grouping-key() returns a false.

current-grouping-key() returns either true or false, depending on the current group. In your first example, current-grouping-key() will be true for any group of adjacent p elements of class "code", false for the other groups.

What is the purpose of using a boolean function in group-adjancent ?

Without this, the grouping key would be the result of evaluating the expression self::p[@class = 'code'] which returns an empty sequence, which in turn causes an error.

michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
  • Thank you! Very helpful Does this mean when boolean function is used, only 2 groups are created (true group and false group) ? – StillStumbling Apr 22 '15 at 20:28
  • No, you get a new group every time you find an element for which the condition has a different value from the previous element. – Michael Kay Apr 22 '15 at 22:22