user3219897
user3219897

Reputation: 161

Update an XSLT to incorporate template calling

I am editing an xslt in C#. It has a template "Get" defined in it. I want to call this template and pass it into a variable.

Template:

<xsl:template name="Get">

 <xsl:param name="varMonth" />
  <xsl:choose>
      <xsl:when test="$varMonth='JAN'">
        <xsl:value-of select="'A'" />
      </xsl:when>
 </xsl:choose>
</xsl:template>

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<DocumentElement>
  <PositionMaster>
        <xsl:variable name="varName">
          <xsl:value-of select="''" />
        </xsl:variable>
  </PositionMaster>    
</DocumentElement>
</xsl:template>

</xsl:stylesheet>

Code: I am getting a string as an input to the param of the template

string input = "A";
XmlDocument xslDoc = new XmlDocument();
xslDoc.Load("a.xslt");
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xslDoc.NameTable);
nsMgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
XmlElement valueOf = (XmlElement)xslDoc.SelectSingleNode("/xsl:stylesheet/xsl:template[@match = '/']/DocumentElement/PositionMaster/xsl:variable[@name = "varName"]/xsl:value-of", nsMgr);

if (valueOf != null)
{
// What should i write here to get the below modified XSLT
}

Required XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
  <DocumentElement>
   <PositionMaster>
        <xsl:variable name="varName">
           <xsl:call-template name="Get">
             <xsl:with-param name="Month" select="input"/>
           </xsl:call-template>
        </xsl:variable>
   </PositionMaster>    
  </DocumentElement>
 </xsl:template>
</xsl:stylesheet>

Upvotes: 3

Views: 94

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

Am I right in understanding that you want to transform the stylesheet using C# code? That seems crazy; you are using XSLT, so you have an XML transformation language at your disposal: use it!

However, I'm confused because neither your original stylesheet nor your modified stylesheet is valid XSLT. You can't have a <DocumentElement> element as a child of xsl:stylesheet; it surely needs to be inside a template.

Transforming XSLT stylesheets using XSLT is common practice and it can be a smart approach to some problems. However, it is often done when there are better techniques available, for example adding stylesheet parameters (global xsl:param elements).

Upvotes: 1

Related Questions