Home > Net >  How can i use csharp code in xslt to transform xml in Online transformer
How can i use csharp code in xslt to transform xml in Online transformer

Time:06-10

My code is working on visual studio but I don't want to depend on visual studio. When I transform the same code in an online transformer I'm getting this error.

XPST0017 XPath syntax error at char 0 on line 14 near {...:CurrentDateTime('yyyy-MM-d...}:
Cannot find a matching 1-argument function named {urn:my-scripts}CurrentDateTime()

Here is the link to the online transformer with the code

If the site is not working here is the code

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" 
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"                 
            xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
            xmlns:csharp="urn:my-scripts" 
            exclude-result-prefixes="msxsl csharp">

<xsl:template match="/Employees">

    <xsl:variable name="sDate" select="string(Employee/@date)"/>
    <xsl:variable name="stringDate" select="string($sDate)"/>
    
    <p><xsl:value-of select="$stringDate"/></p>
    <xsl:value-of select="csharp:CurrentDateTime('yyyy-MM-dd')"/>
</xsl:template>

<msxsl:script language="C#" implements-prefix="csharp">
<msxsl:assembly name="System.Core"/>
<msxsl:assembly name="System.Xml.Linq"/>
<msxsl:assembly name="System.Linq"/>
<msxsl:assembly name="System.Collections"/>
<msxsl:using namespace="System.Linq"/>
<msxsl:using namespace="System.Xml.Linq"/>
<msxsl:using namespace="System.Collections.Generic"/>
<msxsl:using namespace="System.Globalization"/>
<![CDATA[

   public string CurrentDateTime(string format)
   {
        // default format
        if (string.IsNullOrEmpty(format)) {
            format = "dd-MM-yyyy";
        }

        return DateTime.Now.ToString(format);
   }
 ]]>
</msxsl:script>
</xsl:stylesheet>

CodePudding user response:

I think the default engine on that site might not support the features you're using. Changing to Xalan 2.7.1 (at the top between Share and Help) got me the below output.

<?xml version="1.0" encoding="UTF-8"?><p>12-Jan-2022</p>

CodePudding user response:

You say:

My code is working on visual studio but I don't want to depend on visual studio.

Your code as written is not dependent on visual studio, but it is dependent on Microsoft XSLT extensions. If you want your code to be portable you are going to have to get rid of these dependencies, in particular the use of msxsl:script.

In XSLT 2.0 you can do what you are trying to achieve using the current-dateTime() and format-dateTime() functions (though the formatting string will be a bit different). If you do this, however, you won't be able to use the Microsoft XSLT processors, which only support XSLT 1.0.

  • Related