Click here to Skip to main content
15,897,371 members
Articles / Programming Languages / XML

XML Serialization of Complex .NET Objects

Rate me:
Please Sign up or sign in to vote.
4.86/5 (16 votes)
19 Oct 2008CPOL17 min read 132.3K   2.6K   61  
Yet another custom XML serializer, with a slightly different approach.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using CustomXmlSerializerTester;

namespace CommonLibrary
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1 t = Test1.Get();//new Test1();
            t.A = 1;
            t.B = 2;
            t.Str = "this is a string";
            t.Dt1 = DateTime.Now;
            t.Dt2 = DateTime.Today.AddDays(10);
            t.Arr = new int[] { 1,2,3 };
            t.baseInt = 33;
            t.baseStr = "this is a basestring";
            t.SetValues(15, 3.4);
            t.privDbl = 5.6;
            t.base1 = new Base1();
            t.base1.baseInt = 99;
            t.base1.baseStr = "base1's basestring";
            t.base2 = t.base1;
            t.tEnum = TestEnum.enum2;

            XmlDocument doc = CustomXmlSerializer.Serialize(t, 1, "Test1");
            doc.Save(@"f:\out.xml");

            Test1 t2 = (Test1)CustomXmlDeserializer.Deserialize(doc.OuterXml, 1, new TestMeTypeConverter());            
        }
    }    

    //[XmlIgnoreBaseType]
    class Base1
    {
        public int baseInt;
        public string baseStr;
        protected int protInt = 1;
        private double privDbl = 2.3;        

        public void SetValues(int prot, double priv)
        {
            protInt = prot;
            privDbl = priv;
        }
    }

    //[CustomXmlSerializationOptions(true, false)]
    class Test1 : Base1
    {
        private Test1()
        { }

        public static Test1 Get()
        {
            return new Test1();
        }

        public TestEnum tEnum;
        public int A;
        public int B;
        public string Str;
        public DateTime Dt1;
        public DateTime Dt2;
        public int[] Arr;
        public double privDbl;
        public Base1 base1;
        public Base1 base2;
    }

    enum TestEnum
    {
        enum1 = 1,
        enum2 = 2
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions