how to use XslCompiledTransform, XSLT in c# (server side), and how to use it with Sharepoint

scenario 1: I just want to do XSLT in server side:
in most examples on the web u'll see stuff like this:

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("output.xsl");

// Execute the transform and output the results to a file.
xslt.Transform("books.xml", "books.html");
 
now many times u'll and want to use the XmlReader and the XmlWriter classes, and there u'll start getting exceptions. The main reason is that those 2 classes really check for your XML, XSL and the output, so unless ur a goody good boy with XML-XSL its really annoying. One main example is that in my scenario I want to create a chunk of HTML but as a DIV, not a whole document, so you need to explicitly tell that to the result output.

so there r ways to continue and be a goody good boy and the only place I found good and exact info about all that is here: http://stackoverflow.com/questions/6214354/problem-with-xslcompiledtransform-and-xslt-in-vb-net/6214764#6214764, THX a lot u guys there!

BUT I chose to take the 1st answer and just skip the output checks by using the Trasform method with this signature:
StringWriter resultSW = new StringWriter();
myXslTrans.Transform(xmlReader, null, resultSW);

with this signature u skip the XmlWriter checks and just write strait into the stream.

scenario 2: SharePoint: they want me to refresh the content of my DataFormWebPart with ajax (yes they r stupid, but they pay), so I want to take my XSLT from the Style Library and in my case I had my XML custom made:

_mainXml.AppendChild(root);
 
string allXmlStr = string.Empty;
using (var stringWriter = new StringWriter())
{
 
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
  {
    _mainXml.WriteTo(xmlTextWriter);
    xmlTextWriter.Flush();
    allXmlStr = stringWriter.GetStringBuilder().ToString();
  }
}


using (XmlReader xmlReader = XmlReader.Create(new StringReader(allXmlStr)))
{
 
using (StringWriter resultSW = new StringWriter())
  {
   
XslCompiledTransform myXslTrans = new XslCompiledTransform();
    string xsl = SPContext.Current.Site.RootWeb.GetFileAsString("/Style%20Library/[subFolderName]/Xsl/Channels.xsl");
    using (StringReader xslSR = new StringReader(xsl))
    {
      using (XmlReader xslReader = XmlReader.Create(xslSR))
      {
        myXslTrans.Load(xslReader);
      }
    }
    myXslTrans.Transform(xmlReader, null, resultSW);
    context.Response.Write(resultSW.GetStringBuilder().ToString()); 
  }
}
 
 

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

Asp.Net Ending Response options, Response.End() vs CompleteRequest()