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=""
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
        <xsl:value-of select="User/UserName"/>
        <xsl:value-of select="User/Password"/>

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");


        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();

            XslCompiledTransform xsltTransform = new XslCompiledTransform();

            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