Introduction
This blog gives us an overall idea of how to compare two dates in XSLT. There may be some cases when we need to add this functionality in XSLT to compare the dates while transforming an XML document to another format. Such things cannot be done in XSLT directly due to the lack of manipulation functions. In order to cure that, Microsoft has provided a way to include C# code directly in XSLT.
Background
In this blog, we will see how we can implement the date comparison functionality in XSLT. Below are the parameters.
This blog gives us an overall idea of how to compare two dates in XSLT. There may be some cases when we need to add this functionality in XSLT to compare the dates while transforming an XML document to another format. Such things cannot be done in XSLT directly due to the lack of manipulation functions. In order to cure that, Microsoft has provided a way to include C# code directly in XSLT.
Background
In this blog, we will see how we can implement the date comparison functionality in XSLT. Below are the parameters.
- Input – XML file with Date element.
- Transform – XSLT: Added C# function to compare date.
- Output - XML File
So basically, we can write C# code in XSLT. We are going to create one C# method that compares two dates. I have created C# method that compares two dates and returns a result.
Syntax
- <?xml version="1.0" encoding="utf-8" ?>
- <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:ClassNameHere="dummy namespace here">
- <msxsl:script language="C#" implements-prefix="ClassNameHere">
- <![CDATA[
- public string MethodName(/* some parameters here*/)
- {
- return /*something*/;
- }
- ]]>
- </msxsl:script>
- <xsl:template match="//Some Node">
- <xsl:value-of select="ClassNameHere:MethodName(SomeNodeHere)" /> </xsl:template>
- </xsl:stylesheet>
Let's create a sample console application to see how it works.
Open Visual Studio and go to File - New Project - Console Application; give it a suitable name, such as - ‘XSLTDateComapre’ and click OK.

Let's create a main XML, i.e., input.xml. Right click on ‘Solution Explorer’ - Add - New Item and select XML file; give it a name like input.xml.

XML Code
- <?xml version="1.0" encoding="utf-8" ?>
- <note>
- <from>[email protected]</from>
- <to>[email protected]</to>
- <cc>[email protected]</cc>
- <bcc>[email protected]</bcc>
- <heading1>Reminder</heading1>
- <heading2>Important</heading2>
- <UpdatedDate>01/06/2018</UpdatedDate>
- <body>Don't forget me this weekend!</body>
- </note>

Viknaraj ManogararajahPosted Jul 22, 2018, 1:53 AM
Nice article, thank you for sharing