ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

WriteToXML

Serializes objects into and from XML documents

Source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ZEMMOURI_Library.Serialization
{
    /// <summary>
    /// Serializes objects into and from XML documents.
    /// </summary>
    public static class XMLSerialization
    {
        #region Serialization

        /// <summary>
        /// Serialize an Object To an XML Document
        /// </summary>
        /// <param name="ObjectToSerialize">The Object To Serialize</param>
        /// <param name="XMLFileName">The path of the Destination XML File</param>
        public static void WriteToXML(this object myObject, string XMLFileName)
        {
            using (TextWriter writer = new StreamWriter(XMLFileName))
            {
                try
                {                    
                    XmlSerializer serializer = new XmlSerializer(myObject.GetType());
                    serializer.Serialize(writer, myObject);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        #endregion    
    }
}

Example

class Program {
 
    internal class Employee {
        public string Name { get; set; }
        public string Department { get; set; }
        public string Function { get; set; }
        public decimal Salary { get; set; }
    }
 
    static void Main(string[] args) {
 
        var l = new List<Employee>() {
            new Employee() { Name = "Mohamed", Department = "R&D", Function = "Trainer", Salary = 2000 },
            new Employee() { Name = "Omar", Department = "R&D", Function = "Trainer", Salary = 3000 },
            new Employee() { Name = "Ali", Department = "Dev", Function = "Developer", Salary = 4000 },
            new Employee() { Name = "Khadidja", Department = "Dev", Function = "Consultant", Salary = 5000 },
            new Employee() { Name = "Wadoud", Department = "R&D", Function = "Developer", Salary = 6000 },
            new Employee() { Name = "Randa", Department = "Dev", Function = "Consultant", Salary = 2000 }};
 
        string fileName="employees.xml";
		l.WriteToXML(fileName);
	   
    }
}

Author: ZEMMOURI

Submitted on: 24 jun. 2018

Language: C#

Type: object

Views: 4448