How to XSL transform a XDocument in C# and VB.NET

To XSL transform a XDocument in C# and VB.NET you can use the snippet below.
A more complex example which also works with custom namespaces can be found HERE.

Sample C#

public XDocument TransformXDocument(XDocument inputXml, string xslFile)
{
	try
	{
		var xslt = new XslCompiledTransform();
		var sb = new StringBuilder();
		using (var writer = XmlWriter.Create(sb))
		{
			xslt.Load(xslFile);
			xslt.Transform(inputXml.CreateReader(ReaderOptions.None), writer);
			writer.Close();
			writer.Flush();
		}
		return XDocument.Parse(sb.ToString());
		
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return new XDocument();
	}
}

Sample VB.NET

Public Function TransformXDocument(inputXml As XDocument, xslFile As String) As XDocument
	Try
		Dim xslt = New XslCompiledTransform()
		Dim sb = New StringBuilder()
		Using writer = XmlWriter.Create(sb)
			xslt.Load(xslFile)
			xslt.Transform(inputXml.CreateReader(ReaderOptions.None), writer)
			writer.Close()
			writer.Flush()
		End Using

		Return XDocument.Parse(sb.ToString())
	Catch ex As Exception
		'handle the exception your way
		Return New XDocument()
	End Try
End Function

One thought on “How to XSL transform a XDocument in C# and VB.NET

Leave a Reply