Search code examples
xslt

How do I convert an ISO 8601 duration to seconds using XSLT 1.0


It seems like this is easy to do in XSLT 2.0 but Microsoft in its infinite wisdom doesn't support XSLT 2.0 in Visual Studio 2005.


Solution

  • One option would be to do all the parsing and calculation in XSLT.

    However, another option would be to extend XSLT with a custom script function in C#:

    <?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:myext="urn:myExtension"
                    exclude-result-prefixes="msxsl myext">
    
      <xsl:output method="xml" indent="yes"/>
    
      <msxsl:script language="C#" implements-prefix="myext">
    
        <![CDATA[
    
            public int SecondsFromIsoDuration(string isoDuration)
            {
                // parse and convert here;
            }
    
        ]]>
    
      </msxsl:script>
    
    
      <xsl:template match="@* | node()">
        <root durationInSeconds="{myext:SecondsFromIsoDuration(@duration)}" />
      </xsl:template>
    </xsl:stylesheet>
    

    The script function will be compiled at runtime to a temporary assembly and then executed. However, be aware to cache your XSLT because every XSLT-compilation will create a new assembly which is only unloaded when your application exits.