Home > Software design >  How to generate random number which is same for two set of elements in XSLT?
How to generate random number which is same for two set of elements in XSLT?

Time:02-24

Input:

<paragraph>
      <bq>34152</bq>
      <eq>52325/eq>
      <private type="DOB">SP1</private>
      <bq>12431</bq>
      <abc>EX</abc>
      <eq>31333</eq>
</paragraph>

Expected Output:

<paragraph>
          <bq>55124</bq>
          <eq>55124</eq>
          <private type="DOB">SP1</private>
          <bq>66565</bq>
          <abc>EX</abc>
          <eq>66565</eq>
</paragraph>

How to use apply-templates to generate same random number for every bq and eq set?

CodePudding user response:

In XSLT 3 (e.g. with random-number-generator) it would boil down to

  <xsl:accumulator name="rng" as="map(*)" initial-value="random-number-generator(current-dateTime())">
    <xsl:accumulator-rule match="paragraph/bq" select="$value?next()"/>
  </xsl:accumulator>
  
  <xsl:template match="paragraph/bq | paragraph/eq" expand-text="yes">
    <xsl:copy>{round(accumulator-before('rng')?number * 100000)}</xsl:copy>
  </xsl:template>

  <xsl:mode on-no-match="shallow-copy" use-accumulators="rng"/>

That requires Saxon HE 10 or later or Saxon PE/EE 9.8 or later or Saxon-JS 2.

  • Related