Search code examples
c#xml-deserialization

C# Xml Deserialize, ignore data in XML


During de-serialization, how do I ignore a property? In my case, I don't want the FullName property to get initialized at all. I am not looking for [XMLIgnore] solutions - think it as a scenario where I don't have access to change the class.

Here's my class:

public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
}

Here's how I am initializing:

Person p1 = new Person() { Id = 1, FullName = "P1" };
Person p2 = new Person() { Id = 2, FullName = "P2" };
List<Person> persons = new List<Person> { p, q }; //this object is xml serialized. 

And here's my XML: ( I got it though the XML Serialization)

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Id>1</Id>
    <FullName>P1</FullName>
  </Person>
  <Person>
    <Id>2</Id>
    <FullName>P2</FullName>
  </Person>
</ArrayOfPerson>

Solution

  • You can use a custom XmlReader in the deserialization process that will simply skip over the FullName elements. Something like this:

    public class MyXmlReader : XmlTextReader
    {
        public MyXmlReader(string filePath) : base(filePath)
        {
        }
    
        public override bool Read()
        {
            if (base.Read())
            {
                if (Name == "FullName")
                    return base.Read();
    
                return true;
            }
    
            return false;
        }
    }
    

    Then use it like this

    var serializer = new XmlSerializer(typeof(List<Person>));
    
    using (var reader = new MyXmlReader("XMLFile.xml"))
    {
        var person = (List<Person>)serializer.Deserialize(reader);
    }
    

    You can implement a different constructor to take a stream or whatever you have. It doesn't have to be a file path.