Andrew Truckle
Andrew Truckle

Reputation: 19197

Format the text node as a date using XML and XSL?

I have this example XML data (cut down to the basics):

<?xml version="1.0" encoding="UTF-8"?>
<AssignmentHistory Version="1610">
    <W20160104>
        <Chairman>Name1</Chairman>
    </W20160104>
    <W20160111>
        <Chairman>Name2</Chairman>
    </W20160111>
</AssignmentHistory>

It contains a list of WYYYYNNDD nodes. At the moment I am accessing this list within a XSL script like this (again, this is a cut down example):

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes" version="4.01"
    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    doctype-public="//W3C//DTD XHTML 1.0 Transitional//EN"/>
  <xsl:template match="/">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <!--<link rel="stylesheet" type="text/css" href="Workbook-off.css"/>-->
        <title>Custom Report</title>
      </head>
      <body>
        <xsl:variable name="AssignHistory" select="document('AssignHistory.xml')"/>
        <xsl:for-each select="$AssignHistory/AssignmentHistory/*">
          <xsl:apply-templates select="Chairman"></xsl:apply-templates>
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="Chairman">
    <p>
      <xsl:text>Chairman: </xsl:text>
      <xsl:value-of select="."/>
    </p>
  </xsl:template>
</xsl:stylesheet>

What I want to do is during the for-each loop convert the contents of "." (which would be a value like WYYYYMMDD) and display it as a standard short date (eg. dd/mm/yyyy).

I am not sure how to do this. Thank you for your guidance with this issue. It is appreciated.

Expected result:

04/01/2016
Chairman: Name1
11/01/2016
Chairman: Name2

Eventually things will change and get more complex.

Upvotes: 0

Views: 79

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117165

This is rather trivial - try:

<xsl:template match="Chairman">
    <xsl:variable name="datestr" select="name(..)" />
    <p>
        <xsl:value-of select="substring($datestr, 8, 2)"/>
        <xsl:text>/</xsl:text>
        <xsl:value-of select="substring($datestr, 6, 2)"/>
        <xsl:text>/</xsl:text>
        <xsl:value-of select="substring($datestr, 2, 4)"/>
        <br/>
        <xsl:text>Chairman: </xsl:text>
        <xsl:value-of select="."/>
    </p>
</xsl:template>

Upvotes: 1

Related Questions