cadet
cadet

Reputation: 3

Creating (copying) entire records as many times a a tag value demands

i have a few xml records like below example xml. What i try to do is to add as many records as the tag occurrences has, minus 1. (value of occurrences minus 1 will be the records that will be added). If a record has a tag with occurrences value 5, then we must copy this record four more times into the new xml that will be generated. Plus, in the end, an incremental id of all records must be added, like 1,2,3,4,5,6,7 etc I am now learning xslt 3-0, and would want a solution for xslt 3. I have managed to add an incremental number in all records with xsl count.

    <breakfast_menu>
    <food>
    <name>Belgian Waffles</name>
    <occurrences>1</occurrences>
    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
    </food>
    <food>
    <name>Strawberry Belgian Waffles</name>
    <occurrences>2</occurrences>
    <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
    </food>
</breakfast_menu>

desired output:

<breakfast_menu>
<food>
<id>1</id>
<name>Belgian Waffles</name>
<occurrences>1</occurrences>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<id>2</id>
<name>Strawberry Belgian Waffles</name>
<occurrences>2</occurrences>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<id>3</id>
<name>Strawberry Belgian Waffles</name>
<occurrences>2</occurrences>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>

Upvotes: 0

Views: 49

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Here is a two step transformation:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">
  
  <xsl:template match="breakfast_menu">
    <xsl:copy>
      <xsl:variable name="food">
        <xsl:apply-templates mode="duplicate"/>
      </xsl:variable>
      <xsl:apply-templates select="$food/food"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:mode name="duplicate" on-no-match="shallow-copy"/>
  
  <xsl:template mode="duplicate" match="food">
    <xsl:copy-of select="(1 to occurrences) ! current()"/>
  </xsl:template>
  
  <xsl:template match="food">
    <xsl:copy>
      <id><xsl:number/></id>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:mode on-no-match="shallow-copy"/>
  
  <xsl:output indent="yes"/>
  
</xsl:stylesheet>

Upvotes: 0

Related Questions