Click here to Skip to main content
14,970,219 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends

Please help me to create a class so that after serialization i will get a xml of format this:
<?xml version="1.0" encoding="UTF-8" ?>
<Message Command="Point Deposit" UnitID="0000" Version="1.6">
  <TimeDate>09/02/2004 08:13:52 AM</TimeDate>
  <Error />
  <PlayerName>Doe John</PlayerName>
Updated 7-Oct-13 9:31am

the following is the code sample i tested that code. You just add your required property as you like

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

namespace ConsoleApp2912
    class Program
        static void Main(string[] args)
            var data = new Message();
            data.Command = "Point Deposit";
            data.Version = "1.6";
            data.UnitId = "0000";
            data.Status = "GOOD";
            data.Amount = 200;

            var serializer = new XmlSerializer(typeof (Message));

            using (var strem = new FileStream("d:\\data.xml", FileMode.OpenOrCreate))
                serializer.Serialize(strem, data);


    [XmlRoot(ElementName = "Message")]
    public class Message
        [XmlAttribute(AttributeName = "Command")]
        public string Command { get; set; }

        [XmlAttribute(AttributeName = "UnitID")]
        public string UnitId { get; set; }

        [XmlAttribute(AttributeName = "Version")]
        public string Version { get; set; }

        [XmlElement(ElementName = "Status")]
        public string Status { get; set; }

        [XmlElement(ElementName = "Amount")]
        public long Amount { get; set; }
If you want the most comprehensive solution which is the easiest to use at the same time, don't use XmlSeializer, use Data Contract instead:[^].

Please see also my past answers where I advocate this approach:
Creating property files...[^],
How can I utilize XML File streamwriter and reader in my form application?[^].


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900