简体   繁体   中英

Sequence number for static and dynamic rows in XSLT 2.0

I'm trying to generate sequence number for my input xml with some static and dynamic rows combination.

input xml: (Edited)

<data>
  <oldLine>dat1</oldLine>
  <modLine>dat2</modLine>
  <line>para1</line>
  <line>para2</line>
  <line>para3</line>
</data>
<data>
   <oldLine>dat3</oldLine>
   <modLine>dat4</modLine>
   <line>para4</line>
   <line>para5</line>
</data>

I need to add three fixed records after every "data" tag in the loop but sequence number should be continuous and consider only "line" tags for sequence.

Required output text file:

00001 para1
00002 para2
00003 para3
00004 static1
00005 static2
00006 static3
00007 para4
00008 para5
00009 static1
00010 static2
00011 static3

I've tried in my xsl as:

<xsl:for-each select="data">
   <xsl:for-each select="line">
     <xsl:value-of select="format-number(position(),"00000")"/>
     <xsl:value-of select="."/>
     <xsl:text>%#x0A</xsl:text>
   </xsl:for-each>
   <xsl:value-of select="format-number(position(),"00000")"/>
   <xsl:text>static1</xsl:text>
   <xsl:text>%#x0A</xsl:text>
   <xsl:value-of select="format-number(position(),"00000")"/>
   <xsl:text>static2</xsl:text>
   <xsl:text>%#x0A</xsl:text>
   <xsl:value-of select="format-number(position(),"00000")"/>
   <xsl:text>static3</xsl:text>
   <xsl:text>%#x0A</xsl:text>
</xsl:for-each>

But according to my xsl i was not able to generate the sequence number continuously for all rows. please help me in finding the logic behind it.

Would this XSLT do:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:apply-templates select=".//line"/>
    </xsl:template>

    <xsl:template match="line">
        <xsl:variable name="pos" select="position() + (3 * count(preceding::data))"/>
        <xsl:value-of select="concat(format-number($pos, '00000 '), ., '&#xa;')"/>
    </xsl:template>

    <xsl:template match="data/line[last()]">
        <xsl:variable name="pos" select="position() + (3 * count(preceding::data))"/>
        <xsl:value-of select="concat(format-number($pos, '00000 '), ., '&#xa;')"/>
        <xsl:value-of select="concat(format-number($pos+1, '00000 '), 'static1', '&#xa;')"/>
        <xsl:value-of select="concat(format-number($pos+2, '00000 '), 'static2', '&#xa;')"/>
        <xsl:value-of select="concat(format-number($pos+3, '00000 '), 'static3', '&#xa;')"/>
    </xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM