|
HTML clipboard
HTML clipboard
CustomDate custDate = new CustomDate() ;
2) Provide a custom namespace declaration for the custom class
within XSLTs namespace declaration(in XSLT file)
<xsl:transform
version="1.0"
xmlns:xsl="http:
xmlns:myCustDate="urn:custDate">
3) Pass an instance of the custom object to XSLT, with the same namespace
as in last step(in C#)
xslArgs.AddExtensionObject("urn:custDate", custDate) ;
4) Use the object from within XSLT(in XSLT file)
<xsl:value-of select="myCustDate:GetDateDiff(./joiningdate)"/>
Sample code
For our example let us assume we have a XSLT sheet where we need to manipulate dates.
We need to show the number of days the employee has been with the company.
Since XSLT has no native date manipulation functions,
let us use an extension object for our task. using System ;
using System.IO ;
using System.Xml ;
using System.Xml.Xsl ;
using System.Xml.XPath ;
public class XsltExtension{
public static void Main(string[] args){
if (args.Length == 2){
Transform(args[0], args[1]) ;
}else{
PrintUsage() ;
}
}
public static void Transform(string sXmlPath, string sXslPath){
try{
new XPathDocument(sXmlPath) ;
XslTransform myXslTrans = new XslTransform() ;
new XsltArgumentList() ;
new CustomDate() ;
new XmlTextWriter("extendXSLT.html", null) ;
catch(Exception e){
Console.WriteLine("Exception: {0}", e.ToString());
}
}
public static void PrintUsage(){
Console.WriteLine("Usage: XsltExtension.exe <xml path> >xsl path<") ;
}
}
public class CustomDate{
public string GetDateDiff(string xslDate){
DateTime dtDOB = DateTime.Parse(xslDate) ;
DateTime dtNow = DateTime.Today ;
TimeSpan tsAge = dtNow.Subtract(dtDOB) ;
return tsAge.Days.ToString() ;
}
}
XPathDocument myXPathDoc =
myXslTrans.Load(sXslPath) ;
XsltArgumentList xslArgs =
CustomDate custDate =
xslArgs.AddExtensionObject("urn:custDate", custDate) ;
XmlTextWriter myWriter =
myXslTrans.Transform(myXPathDoc,xslArgs, myWriter) ;
myWriter.Close() ;
}
|