How to enable XSLT scripting in C# ..? - c#

I have modified the title of the question after finding the answer :) :P
I am loading an XML file and an XSL file by a C# program and triggering the XSL transformation .. here is the code for it:
static void Main(string[] args)
{
// Create the XslCompiledTransform and load the stylesheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("input.xsl"); //located in Debug folder
//Load XSL argument list
XsltArgumentList xslArg = new XsltArgumentList();
// Transform the file.
using (XmlWriter w = XmlWriter.Create("output.xml"))
{
xslt.Transform("input.xml", xslArg, w); //located in Debug folder
}
}
The error is I am not able to load XML file.
The XSL file contains some C# code which is meant to calculate the difference between two DateTime strings .. well, I can transform the XML file manually using the same XSL file .. But when I try to trigger the transformation using C# code .. then it says "It can't load XML file"
Here is my (part of) XSL code ..
<span bgcolor="#EEEEEE">
<xsl:variable name="date1" select="//date1"/>
<xsl:variable name="date2" select="//date2"/>
<msxsl:script language="C#" implements-prefix="cs">
<![CDATA[
public string datediff(string date1, string date2) {
DateTime startTime = new DateTime(Convert.ToInt32(date1.Substring(6, 4)), Convert.ToInt32(date1.Substring(0, 2)), Convert.ToInt32(date1.Substring(3, 2)), Convert.ToInt32(date1.Substring(11, 2)), Convert.ToInt32(date1.Substring(14, 2)), Convert.ToInt32(date1.Substring(17, 2)), 0);
DateTime endTime = new DateTime(Convert.ToInt32(date2.Substring(6, 4)), Convert.ToInt32(date2.Substring(0, 2)), Convert.ToInt32(date2.Substring(3, 2)), Convert.ToInt32(date2.Substring(11, 2)), Convert.ToInt32(date2.Substring(14, 2)), Convert.ToInt32(date2.Substring(17, 2)), 0);
return(endTime.Subtract(startTime));
}
]]>
</msxsl:script><br>
<xsl:template match="datediff"><br>
<xsl:element name="{local-name()}"><br>
<xsl:value-of select="cs:datediff($date1, $date2)" /><br>
</xsl:element><br>
</xsl:template><br></span>
Is that, because of script(C# code to calculate date diff..) I am getting this error?By the way C# code runs perfectly when I use some other input XML and XSL files ..
please help me to overcome this error ..

As Steve cooper has mentioned .. you need to enable the XSLT script .. and here is the way to do it:
first define a new settings instance:
var settings = new XsltSettings();
then enable the script
settings.EnableScript = true;
Create the XslCompiledTransform object and load the style sheet, passing in the settings object.

In the MSDN Documentation it says "XSLT scripting is disabled by default. XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment."
This is probably your problem. Try loading the transform like this;
XslCompiledTransform xslt = new XslCompiledTransform();
// Disable script blocks and the document() function
// if a stylesheet came from an untrusted source
string untrustedUri = #"http://www.untrusted-site.com/meow.xsl";
XmlResolver secureResolver = new XmlSecureResolver(new XmlUrlResolver(), untrustedUri);
xslt.Load(untrustedUri, XsltSettings.Default, secureResolver);
// Enable script blocks and the document() function
// if a trusted stylesheet needs them
xslt.Load(#"C:\MyProject\purr.xsl", XsltSettings.TrustedXslt, new XmlUrlResolver());
You could add some detail to your question, too; can you say how you are able to do it manually? What program or engine are you using? For instance, XMLSpy uses a different transform engine from the .Net framework, so XSL files can be incompatable.

Define the settings variable Enabling Script Mode and then use it in the load process.
var settings = new XsltSettings();
settings.EnableScript = true;
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("input.xsl", settings , null);
It worked for me.
Regards!

I would suggest trying to load the XML file completely separately - I wouldn't be surprised to find that this had nothing at all to do with XSL, and everything to do with it not being able to find the file or something similar.
Try loading the XML file into an XmlDocument and checking that it looks correct. If that works, use the overload accepting an IXPathNavigable as input (XmlDocument implements IXPathNavigable).

Related

XSL + XML -> PDF for C#

I know several people asked questions like this, but no answer helped to solve my problem.
Well, I have xsl and xml and want to generate pdf with a processor like Apache.FOP.
I am not able to use any JAVA programms like that. Just able to use C# libraries / exe.
I tried to use nFop:
Version 1.x uses Java.io and..
Version 2.0 doesn't have the ability to set XsltSettings
My current Software uses XSL + XML -> HTML (using standard Stystm.Xml.Xsl on C#) and wktmltopdf to generate PDF from created HTML.
But tables got split when they are too long for the page, and on the next page you don't have any column headers (this is very important for my problem).
I think there are no Free FO-Processor for pure C
Have a look at FoNET.
public static bool XMLToPDF(string pXmlFile, string pXslFile, string pFoFile, string pPdfFile)
{
string lBaseDir = System.IO.Path.GetDirectoryName(pXslFile);
XslCompiledTransform lXslt = new XslCompiledTransform();
lXslt.Load(pXslFile);
lXslt.Transform(pXmlFile, pFoFile);
FileStream lFileInputStreamFo = new FileStream(pFoFile, FileMode.Open);
FileStream lFileOutputStreamPDF = new FileStream(pPdfFile, FileMode.Create);
FonetDriver lDriver = FonetDriver.Make();
lDriver.BaseDirectory = new DirectoryInfo(lBaseDir);
lDriver.CloseOnExit = true;
lDriver.Render(lFileInputStreamFo, lFileOutputStreamPDF);
lFileInputStreamFo.Close();
lFileOutputStreamPDF.Close();
return System.IO.File.Exists(pPdfFile);
}

How to transform XMLDocument using XSLT in C# 2.0

I am using C# 2.0 and I have got below code:
XmlDocument doc = new XmlDocument();
doc.LoadXml(GetListOfPagesInStructureGroup(m_Page.Id));
In above I am loading my XMLDocument with method which returns as string, now after some processing on above xmldocument I want to apply XSLT on the above XMLDocument to render my desired result according to XSLT and finally my function will return whole rendered XML as string
Please suggest!!
Please suggest on below solution:
XslCompiledTransform xslTransform = new XslCompiledTransform();
StringWriter writer = new StringWriter();
xslTransform.Load("xslt/RenderDestinationTabXML.xslt");
xslTransform.Transform(doc.CreateNavigator(),null, writer);
return writer.ToString();
Thanks!!
Try the XslCompiledTransform class.
There are lots of examples on the web of transforming an XML file to a different format using an XSLT file, like the following:
XslTransform myXslTransform = new XslTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load("transform.xsl");
myXslTransform.Transform("input.xml", "output.xml");
However this is only a partial answer, I would like to be able to get the XML input data from a web form and use that as the input data instead of an '.xml' file, but have not found any concrete examples, also using Visual Studio I can see the different constructors and methods that are available and I am not seeing one that accepts xml data in a string format, so it would be very helpful if someone could provide an example of that.
Re " I want my same XMlDocument updated " - it doesn't work like that; the output is separate to the input. If that is important, just use a StringWriter or MemoryStream as the destination, then reload the XmlDocument from the generated output.
Consider in particular: the output from an xslt transformation does not have to be xml, and also: the xslt is most likely using the node tree during the operation; changing the structure in-place would make that very hard.

No stylesheet was loaded

I am using C# code in aspx pages to covert the infopath xml pages into html. Here is my code:
XPathDocument myDoc = new XPathDocument(#"C:\Users\rameshgandhik\Documents\infopath forms\ram.xml");
XmlTextWriter myWr = new XmlTextWriter(#"C:\Users\rameshgandhik\Documents\infopath forms\ram.html",null);
XslTransform myXsl = new XslTransform();
myXsl.Transform(myDoc, null, myWr); // Here i am getting an error.
At myWr in Transform method it is showing an error that
"No stylesheet was loaded.".
Can any have the idea about this error......... Please tell me the solution....
That would be because you haven't loaded the stylesheet. :-)
You've created a new XslTransform object, but you didn't actually put any transformation rules into it. Therefore, it doesn't know how to transform the XML you're giving it, which is pretty clearly expressed in the error message.
If you want to take the transform from an *.xsl file, you can use the XslTransform.Load method.
If you want to get the transform from some other location, please specify what that location is, and I would probably be able to help you.

Programmatically read from library

I have a document library named "xsl library" with a bunch of xsl's... and I need to read a file (anyone one) from there so I can use it transform a xml that renders a webpart... the layout out of a webpart is determined by the xsl... how can I do it?
Notes: Enviroment -> Sharepoint 2007
So it looks like you need some server side code:
SPFile xslFile = SPContext.Current.Web.GetFile("/myWeb/myXlsLibrary/myXsl.xsl");
Stream xslStream = xslFile.OpenBinaryStream();
Then you code similar to one provided by Vlad above to make the transformation.
See MSDN for more info on functions used - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getfile.aspx , http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.openbinarystream.aspx.
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load(XmlReader.Create(new StringReader(stringWithXsltStylesheetCode)));
XmlDocument result = new XmlDocument();
using (XmlWriter xw = result.CreateNavigator().AppendChild())
{
proc.Transform(inputXmlDocument, null, xw);
xw.Close();
}

XSLT and XML Question

I have this kinda interesting requirement.
Typically you use XSLT to transform an XML document. The transformed HTML is viewable in a web browser, this works just great. I am also guessing the browser handles the transformation in memory, because if you view the page source of an xml document with XSLT, you don't see html, only xml.
What I would like to do is the following.
using c#
grab an xml file from the fileSystem....
Load it into some framework object
attach an XSLT stylesheet
output the rendered HTML back to an html file on the file system.
Is this possible.
I don't expect a full answer on the entire solution. Just a push in the right direction would be great :) thanks in advance.
You can use System.Xml.Xsl to do XSLT in C#.
There's an article here: XML transformation using Xslt in C# that explains how - here's the core of it:
XPathDocument myXPathDoc = new XPathDocument(<xml file path>);
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(<xsl file path>);
XmlTextWriter myWriter = new XmlTextWriter("result.html", null);
myXslTrans.Transform(myXPathDoc, null, myWriter);
(Edit: Note to #John: that code illustrates the basic idea. It doesn't pretend to be production quality.)
So, I found the answer, and pretty quickly... Its all explained here...
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
what if the html is a invaild format xml?
it looks like we can not use xslt?
Any feedbacks?

Categories

Resources