0

I'm new to XSLT.
I have a source XSLT like the below one.

<?xml version="1.0" encoding="UTF-8"?> 
   <root>
      <child-value>3</child-value>
   </root>

My target should have something like the below one

<?xml version="1.0" encoding="UTF-8"?> 
 <pass_details>
    <pass id ='p1'>1</pass>
    <pass id ='p2'>2</pass>
    <pass id ='p3'>3</pass>
 </pass_details>

The number of <pass> tag should be based on the value of child-value tag? Can any one help with the xslt?

1
  • Where is this related to xquery after all? Please restrict to relevant tags. Commented Jul 3, 2016 at 10:06

1 Answer 1

4

If you're limited to XSLT 1.0, you will have to call a recursive template to generate the pass elements:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <pass_details>
        <xsl:call-template name="gen">
            <xsl:with-param name="n" select="child-value"/>
        </xsl:call-template>
    </pass_details>
</xsl:template>

<xsl:template name="gen">
    <xsl:param name="n"/>
    <xsl:if test="$n > 0">
        <xsl:call-template name="gen">
            <xsl:with-param name="n" select="$n - 1"/>
        </xsl:call-template>
        <pass id="p{$n}">
            <xsl:value-of select="$n"/>
        </pass>
    </xsl:if>   
</xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @michael.hor257k. this wrks. One more doubt, Is there any way to convert the date which is string into xsd:date sourceXML : <endDate>2016-07-08T02:05:58.058Z</endDate> targetXML must have <endDate>2016-07-08+05:58</endDate> . In source it is string, where the target expect this as xsd:date. any suggestions.
I am sure there is - but please post this as a new question.
I have a doubt on the execution of the above xsl. How does the executon happens for the '<xsl:if test="$n > 0"> <xsl:call-template name="gen"> <xsl:with-param name="n" select="$n - 1"/> </xsl:call-template> <pass id="p{$n}"> <xsl:value-of select="$n"/> </pass> </xsl:if> ' whether template will be called first or the pass tag will be executed then the template is called. suggest any tutorial for xslt. thanks
The recursive call is executed before outputting the pass element. That is because the counter is counting backwards: 3 , 2, 1, and you want the output in reverse order: 1, 2, 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.