XmlSerializer UnknownNode Event

The UnknownNode Event occurs when calling Deserialize and the xml contains nodes that do not exist in the type class. By default the XmlSerializer ignores unknown XML nodes, so this event gives you the ability to handle them.

Below is a example of how to use it:


    public class Person
    {
        public int Age;
        public string Forname;
        public string Surname;
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Person p = new Person();
            p.Forname = "John";
            p.Surname = "Smith";
            p.Age = 20;

            Serialize(p);

            Person p2 = Deserialize();

            Console.WriteLine("Name: " + p2.Forname + " " + p2.Surname + ", aged: " + p.Age);
            Console.ReadKey();
        }

        private static void Serialize(Person person)
        {
            StreamWriter streamWriter = new StreamWriter("person.xml");

            XmlSerializer xmlSerializer = new XmlSerializer(typeof (Person));
            xmlSerializer.Serialize(streamWriter, person);

            streamWriter.Dispose();
        }

        private static Person Deserialize()
        {
            StreamReader streamReader = new StreamReader("person.xml");

            XmlSerializer xmlSerializer = new XmlSerializer(typeof (Person));
            xmlSerializer.UnknownNode += XmlSerializerUnknownNode;
            Person person = (Person) xmlSerializer.Deserialize(streamReader);

            streamReader.Dispose();

            return person;
        }

        private static void XmlSerializerUnknownNode(object sender, XmlNodeEventArgs e)
        {
            if (e.Name == "DateOfBirth")
            {
                //Handle Date of Birth
            }
        }
    }



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.