2

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>
Sekhar
  • 5,614
  • 9
  • 38
  • 44
  • A very brutish solution (if you don't have too many properties in your actual code) would be to create a new _temporary_ class, e.g. Person2, with all fields except the one you want to ignore. Use that for serializing. While deserializing you can still use the original class. it will just leave your ignored value as null. However, if the name of the class is important for you in the XML, this suggestion won't be useful. – Keyur PATEL Feb 16 '17 at 02:27
  • This could help you if my first suggestion doesn't. [Ignore a property during xml serialization but not during deserialization](http://stackoverflow.com/a/18242538/6741868). Another example of the same Override method is [Ignore a property when serializing to XML](http://stackoverflow.com/a/23121696/6741868) – Keyur PATEL Feb 16 '17 at 02:31
  • thanks for your inputs, but the XMLAttributeOverrides helps when the element name in the xml is different than the class property name. – Sekhar Feb 16 '17 at 02:59

1 Answers1

2

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.

Mike Hixson
  • 5,071
  • 1
  • 19
  • 24