How to apply an XSLT Stylesheet in C#
Asked Answered
S

5

204

I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

Severn answered 29/8, 2008 at 7:10 Comment(2)
Actually, I think this is a great question, and you provided a good answer. Nominating for reopen.Wanwand
I found Xslt confusing, so this helped me github.com/beto-rodriguez/SuperXmlCollazo
S
187

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
Severn answered 29/8, 2008 at 7:10 Comment(3)
Since I took some of your answer to make the class that I'm linking to, thought I'd put it as a comment here. Hopefully it simplifies things for people: dftr.ca/?p=318Madagascar
I prefer this solution instead of the overloaded version because you are able to set XmlReaderSettings and XmlWriterSettings using DTD, Schemas, etc.Plainlaid
I need to do this in VB.NET (which is my "offspec" language, I prefer C#), and your answer led to my solution. ThanksStunner
A
147

Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Load("stylesheet.xsl"); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

With New XslCompiledTransform()
    .Load("stylesheet.xsl")
    .Transform("source.xml", "result.html")
End With
Aposematic answered 15/5, 2012 at 7:40 Comment(0)
P
15

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Pitts answered 26/10, 2010 at 10:55 Comment(2)
This is a link-only answer. Please include the relevant parts of the linked pages.Embosom
Two of the links are dead.Infirmary
V
4

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   
Vasili answered 19/11, 2019 at 9:34 Comment(4)
what's difference between doc and document.DocumentElement.OuterXml?Schipperke
doc is defined as string doc is the parameter to this function which is passed to the Func<string,XmlDocument> GetXmlDocument which loads and returns XmlDocument type. document.DocumentElement is a property of type XmlElement and OuterXml is an string property of XmlElement to get the string. REf [learn.microsoft.com/en-us/dotnet/api/…Vasili
correct answer is nothing... there's no difference between them and both are exactly same value... so you don't need to deserialize doc to XmlDocument and extracting back same xml with OuterXml...Schipperke
@Schipperke The correct answer is: the Transform method is overridden in 15 different forms and you can use anyone of it. Yes, it can be called as Transform(string,string) also that doesn't make things correct. The xslt is drafted but xml is the businessdata the Func here ensures that the data is proper xml then to be blind. I had a logger there just to log that. Refer for Transform [docs.microsoft.com/en-us/dotnet/api/…Vasili
N
0

I would like to share this small piece of code which reads from Database and transforms using XSLT. On the top I also have used xslt-extensions which makes it little different than others.

Note: This is just a draft code and may need cleanup before using in production.

var schema = XDocument.Load(XsltPath);
using (var connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    using (var command = new SqlCommand(Sql, connection))
    {
        var reader = command.ExecuteReader();
        var dt = new DataTable(SourceNode);
        dt.Load(reader);
                    
        string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine;
        using (var stringWriter = new StringWriter())
        {
            dt.WriteXml(stringWriter, true);
            xml += stringWriter.GetStringBuilder().ToString();
        }

        XDocument transformedXml = new XDocument();
        var xsltArgumentList = new XsltArgumentList();
        xsltArgumentList.AddExtensionObject("urn:xslt-extensions", new XsltExtensions());

        using (XmlWriter writer = transformedXml.CreateWriter())
        {
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(schema.CreateReader());
            xslt.Transform(XmlReader.Create(new StringReader(xml)), xsltArgumentList, writer);
        }
        var result = transformedXml.ToString();
    }
}

XsltPath is path to your xslt file.
ConnectionString constant is pointing to your database.
Sql is your query.
SourceNode is node of each record in source xml.

Now the interesting part, please note the use of urn:xslt-extensions and new XsltExtensions() in above code. You can use this if need some complex computation which may not be possible in xslt. Following is a simple method to format date.

public class XsltExtensions
{
    public string FormatDate(string dateString, string format)
    {
        DateTime date;

        if (DateTime.TryParse(dateString, out date))
            return date.ToString(format);

        return dateString;
    }
}

In XSLT file you can use it as below;

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="urn:xslt-extensions">
...
<myTag><xsl:value-of select="ext:FormatDate(record_date, 'yyyy-MM-dd')"/></myTag>
...
</xsl:stylesheet>
Nablus answered 8/7, 2022 at 0:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.