Coding with passion

首页 新随笔 联系 订阅 管理

When I serialized an object into an XML string using XmlSerializer recently, I found that all the fields which were marked with the ObsoleteAttribute were ignored by XmlSerializer. I couldn't find the associated attributes in the XML string. After some tests, I found that XmlSerailzer would ignore these fields both in the serialization process and the deserialization process, just like they were marked with XmlIgnoreAttributes. This should be a undocumented feature for .NET.

Let's do some test about this. For example, we have a class called Employee.

public class Employee
{
  private string _name;
  private int _id;

  [Obsolete]
  [XmlAttribute("name")]
  public string Name
  {
    get { return _name; }
    set { _name = value; }
  }

  [XmlAttribute("id")]
  public int ID
  {
    get { return _id; }
    set { _id = value; }
  }
}

private static void Main()
{
  // Serializes an Employee object into an XML string
  Employee e = new Employee();
  e.ID = 10;
  e.Name = "Employee Name";

  XmlSerializer serializer = new XmlSerializer(typeof(Employee));
  using (MemoryStream ms = new MemoryStream()) {
    TextWriter textWriter = new StreamWriter(ms, Encoding.UTF8);
    serializer.Serialize(textWriter, e);

    ms.Seek(0, SeekOrigin.Begin);
    TextReader textReader = new StreamReader(ms, Encoding.UTF8);
    Console.WriteLine(textReader.ReadToEnd());
  }
}

By making use the code segment above, we can easily serialize an object into an XML string. If the field "Employee.Name" isn't marked with an ObsoleteAttribute, the serialzied XML looks like:

<?xml version="1.0" encoding="utf-8"?>
<Employee
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  name="Employee Name" id="10" />

We can also get the serialized XML segment after the field "Employee.Name" is marked with an ObsoleteAttribute. Then we can find that the "name" attribute of the "Employee" element in the XML segment is missing. We cannot find it any more. Obviously, the "Employee.Name" property was ignored by XmlSerializer.

So we have known that XmlSerialize will ignore fields which are marked with ObsoleteAttribute when serializing objects. But what will happen for the deserialization process?

string xml = @"<Employee name=""Employee Name"" id=""10"" />";
Employee employee;

using (StringReader sr = new StringReader(xml)) {
  XmlSerializer serializer = new XmlSerializer(typeof(Employee));
  employee = (Employee)serializer.Deserialize(sr);

  Assert.IsNotNull(employee);
}

Console.WriteLine("Employee name: {0}", employee.Name);
Console.WriteLine("Employee ID: {0}", employee.ID);

After executing the code segment, we can find that "employee.Name" is empty. That means XmlSerialize also ignored Employee.Name. The program output is:

Employee name:
Employee ID: 10
posted on 2007-08-28 13:36  Kellin  阅读(1925)  评论(1编辑  收藏  举报