I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.
-
11Actually, I think this is a great question, and you provided a good answer. Nominating for reopen. – Dominic Rodger Dec 22 '09 at 11:56
-
I found Xslt confusing, so this helped me https://github.com/beto-rodriguez/SuperXml – bto.rdz Aug 26 '15 at 18:02
5 Answers
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);

- 11,115
- 12
- 51
- 64

- 67,947
- 40
- 154
- 200
-
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: http://dftr.ca/?p=318 – DFTR Mar 25 '13 at 23:44
-
I prefer this solution instead of the overloaded version because you are able to set [XmlReaderSettings](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings%28v=vs.110%29.aspx) and [XmlWriterSettings](http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings%28v=vs.110%29.aspx) using DTD, Schemas, etc. – Alina B. Oct 11 '14 at 06:09
-
2I need to do this in VB.NET (which is my "offspec" language, I prefer C#), and your answer led to my solution. Thanks – Eon Dec 01 '14 at 10:24
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

- 167,459
- 57
- 363
- 519
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.

- 1,289
- 2
- 14
- 20
-
7This is a link-only answer. Please include the relevant parts of the linked pages. – Thomas Weller Apr 23 '15 at 21:50
-
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;
}
}

- 3,644
- 1
- 27
- 40
-
-
`doc` is defined as `string doc` is the parameter to this function which is passed to the `Func
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 [https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.documentelement?view=net-6.0] – Vinod Srivastav Nov 24 '21 at 23:21 -
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... – sasjaq Nov 25 '21 at 09:50
-
@sasjaq 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 [https://docs.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform.transform?view=net-6.0#System_Xml_Xsl_XslCompiledTransform_Transform_System_Xml_XPath_IXPathNavigable_System_Xml_XmlWriter_] – Vinod Srivastav Nov 25 '21 at 11:01
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>

- 12,300
- 11
- 66
- 95