Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT 2.0 group-adjacent based on attribute value

Tags:

xml

xslt-2.0

I am trying to generate XML using XSLT, I want to generate a string when two consecutive nodes has an attribute value as Position="A", I want to add a hyphen(-) in the string, otherwise I want to concatenate node value. I tried using group-adjacent with attribute value, but it fails on empty attribute node. I tried adding string() for attribute value, but not worked.

<xsl:variable name="columnId">
  <xsl:for-each-group select="CabinLayout/Columns" group-adjacent="string(@Position)">
    <xsl:value-of select="current-group()"/>
  </xsl:for-each-group>
</xsl:variable>
<ColumnID><xsl:value-of select="translate($columnId,' ','-')"/></ColumnID>

Below is the sample input and desired output

<CabinLayout>
  <Columns Position="W">A</Columns>
  <Columns>B</Columns>
  <Columns Position="A">C</Columns>
  <Columns Position="A">D</Columns>
  <Columns>E</Columns>
  <Columns Position="W">F</Columns>
</CabinLayout>

Output- ABC-DEF

<CabinLayout>
  <Columns Position="W">A</Columns>
  <Columns>B</Columns>
  <Columns>C</Columns>
  <Columns Position="A">D</Columns>
  <Columns>E</Columns>
  <Columns>F</Columns>
  <Columns>G</Columns>
  <Columns>H</Columns>
  <Columns>J</Columns>
  <Columns Position="W">K</Columns>
</CabinLayout>

Output : ABCDEFGHJK

<CabinLayout>
  <Columns Position="W">A</Columns>
  <Columns>B</Columns>
  <Columns Position="A">C</Columns>
  <Columns Position="A">D</Columns>
  <Columns>E</Columns>
  <Columns>F</Columns>
  <Columns Position="A">G</Columns>
  <Columns Position="A">H</Columns>
  <Columns>J</Columns>
  <Columns Position="W">K</Columns> 
</CabinLayout>

Output : ABC-DEFG-HJK

like image 264
Umaimath Thonikkadavan Avatar asked Mar 01 '23 13:03

Umaimath Thonikkadavan


1 Answers

I think the following group-ending-with solves that:

  <xsl:template match="CabinLayout">
    <ColumnID>
      <xsl:value-of separator="-">
        <xsl:for-each-group select="Columns" group-ending-with="Columns[@Position = 'A' and following-sibling::Columns[1][@Position = 'A']]">
          <xsl:sequence select="string-join(current-group(), '')"/>
        </xsl:for-each-group>        
      </xsl:value-of>
    </ColumnID>
  </xsl:template>
like image 68
Martin Honnen Avatar answered Mar 07 '23 19:03

Martin Honnen