Need to add <more></more> in the <student> element

Viewed 36

If we get @more="1" attribute in the roll element then <more> element should be add just <following-sibling> of <student>. if @more="2" attribute the add<more> element should be add in the both <following-sibling> <student> element

Input XML:

<kk>
    <kita>
    <student>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll more="1">content here</roll>
    </student>
    <student>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
    </student>
    <student>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
    </student>
    </kita>
</kk>

XSL file:

There are more code in xsl, Just i copied here:

<xsl:if test="parent::student[parent::kita]/following-sibling::student/x:roll[@more]">
    <more/>
</xsl:if>

Expected output:

<?xml version="1.0" encoding="UTF-8"?>
<kk>
    <kita>
    <student>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll more="1">content here</roll>
    </student>
    <student>
        <!-- if @more="1" or @more="2" add <more> element-->
        <more>Content here</more>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
    </student>
    <student>
        <!-- If @more="2" add <more> element below-->
        <more>Content here</more>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
        <roll>content here</roll>
    </student>
    </kita>
</kk>
1 Answers

Try along the lines of

  <xsl:template match="kita">
    <xsl:copy>
      <xsl:for-each-group select="student" group-starting-with="student[roll/@more]">
        <xsl:apply-templates select="current-group()">
          <xsl:with-param name="emit-more" select="xs:integer(roll/@more)"/>
          <xsl:with-param name="more" select="roll[@more]"/>
        </xsl:apply-templates>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="student">
    <xsl:param name="emit-more"/>
    <xsl:param name="more"/>
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:if test="position() - 1 = (1 to $emit-more)">
        <more>
          <xsl:apply-templates select="$more/node()"/>
        </more>
      </xsl:if>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
Related