Transform Object into XML through XSLT in C#

XSLT (Extensible Stylesheet Language Transformations) is used to transform xml from one form to another form. Today we discuss how to transform C# class object into required xml format by applying XSLT transformation.

Open Microsoft Visual Studio 2019 and create console application project. Create below UserInfoTransform.xslt XSLT file in C:\ drive.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <UserInfo>
      <UserName>
        <xsl:value-of select="User/UserName"/>
      </UserName>
      <Password>
        <xsl:value-of select="User/Password"/>
      </Password>      
    </UserInfo>
  </xsl:template>
</xsl:stylesheet>

Add below code to Program.cs class.

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;

namespace XSLTObjectIntoXML
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = new User { UserName = "Raj", Password = "abcd" };

            string xmlInput = ObjectIntoXML(user);

            string xmlOutput = ApplyXSLT(xmlInput, @"C:\UserInfoTransform.xslt");

            Console.WriteLine(xmlOutput);
            Console.ReadLine();
        }

        public static string ObjectIntoXML(object obj)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());

            StringWriter stringWriter = new StringWriter();
            xmlSerializer.Serialize(stringWriter, obj);
            return stringWriter.ToString();
        }

        private static string ApplyXSLT(string xmlInput, string xsltFilePath)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xmlInput);

            XslCompiledTransform xsltTransform = new XslCompiledTransform();
            xsltTransform.Load(xsltFilePath);

            MemoryStream memoreStream = new MemoryStream();
            xsltTransform.Transform(xmlDocument, null, memoreStream);
            memoreStream.Position = 0;

            StreamReader streamReader = new StreamReader(memoreStream);
            return streamReader.ReadToEnd();
        }
    }

    public class User
    {
        public string UserName { get; set; }

        public string Password { get; set; }
    }
}

Here ObjectIntoXML() method converts the User class object into xml and ApplyXSLT() method applies UserInfoTransform.xslt XCSLT transformation on User class object xml and converts it into required XML format as shown below.

ObjectIntoXML() method is using XmlSerializer  to serialize the object and ApplyXSLT() method is using XslCompiledTransform predefined class to apply the XSLT transformation.

Add comment