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;


            Person p2 = Deserialize();

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

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

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


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


            return person;

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


No comments yet.

Add Yours

  • Author Avatar


Comment Arrow

About Author


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.