StillStumbling
StillStumbling

Reputation: 89

Group Adjacent Functionality in XSLT

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 ?

Upvotes: 4

Views: 1003

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 116959

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.

Upvotes: 2

Martin Honnen
Martin Honnen

Reputation: 167436

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.

Upvotes: 5

Related Questions