Charlotte
Charlotte

Reputation: 17

Get the date of each month using xslt

I need to get the date of the each month based on the input file using xslt v2. Here is my sample data:

<Data>
   <Field>March/02/2017/February/16/1989/December/19/2015</Field>
</Data>

My XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Data">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
<xsl:variable name="months" select="'January','February','March','April','May','June','July','August','September','October','November','December'"/>
<xsl:template match="Field">
    <xsl:variable name="Output">
        <xsl:analyze-string select="normalize-space(.)" regex="([A-Z][a-z]+)">
            <xsl:matching-substring>
                <xsl:number value="index-of($months, regex-group(1))" format="01"/>
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:variable>
    <Result>
        <xsl:value-of select="$Output"/>
    </Result>
</xsl:template>
</xsl:stylesheet>

GENERATED OUTPUT

<Data>
   <Result>030212</Result>
</Data>

The output generated is the position of each month, but I want to populate the date after each month. Like this one:

<Data>
   <March>02/2017</March>
   <February>16/1989</February>
   <December>19/2015</December>
</Data>

Also, I'm having a problem if the month in test file is in Upper or lowercase, it didn't populate an output. I

Hope you can help me. Thank you.

Upvotes: 0

Views: 457

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52878

I'm not sure I understand the reason for $months and index-of(). It looks like everything is already in Field.

Example...

XSLT 2.0

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

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Field">
    <xsl:analyze-string select="normalize-space()" regex="(\w+)/(\d{{2}}/\d{{4}})">
      <xsl:matching-substring>
        <xsl:element name="{regex-group(1)}">
          <xsl:value-of select="regex-group(2)"/>
        </xsl:element>
      </xsl:matching-substring>
    </xsl:analyze-string>
  </xsl:template>

</xsl:stylesheet>

Output

<Data>
   <March>02/2017</March>
   <February>16/1989</February>
   <December>19/2015</December>
</Data>

Upvotes: 1

Related Questions