Skip to main content

C# function that transforms XML data using an XSLT Style Sheet, into HTML.

using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;

namespace Xxx.Common.Utils
{
    public static class XmlTransformationUtils
    {
        /// <summary>
        /// Transforms the specified <paramref name="xmlData"/> to HTML using
        /// the specified <paramref name="xslt"/>.
        /// </summary>
        /// <param name="xmlData">The XML data to transform.</param>
        /// <param name="xslt">The XSL Stylesheet.</param>
        /// <returns>The transformed HTML.</returns>
        public static string XmlToHtml(string xmlData, string xslt)
        {
            var xdocTreeResult = new XDocument();

            using (var xmlWriter = xdocTreeResult.CreateWriter())
            {
                var xslCompiledTransform = new XslCompiledTransform();
                xslCompiledTransform.Load(XmlReader.Create(new StringReader(xslt), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto }));
                var parsedXmlData = XDocument.Parse(xmlData, LoadOptions.None);
                xslCompiledTransform.Transform(parsedXmlData.CreateReader(), xmlWriter);
            }

            return xdocTreeResult.ToString();
        }
    }
}