XmlIncludeAttribute.Type Property

Definition

Gets or sets the type of the object to include.

public Type Type { get; set; }
public Type? Type { get; set; }

Property Value

The Type of the object to include.

Examples

The following example defines a class named Group, which contains a field named Employees that returns an array of Employee objects. The example derives the Manager class from the Employee class, and applies the XmlIncludeAttribute to the Employee class. When the example creates a Group object, it inserts a Manager object into the Employee array. Lastly, the example serializes the Group object.

using System;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   public Employee[] Employees;
}

// Instruct the XmlSerializer to accept Manager types as well.
[XmlInclude(typeof(Manager))]
public class Employee
{
   public string Name;
}

public class Manager:Employee
{
   public int Level;
}

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("IncludeExample.xml");
      test.DeserializeObject("IncludeExample.xml");
   }

   public void SerializeObject(string filename)
   {
      XmlSerializer s = new XmlSerializer(typeof(Group));
      TextWriter writer = new StreamWriter(filename);
      Group group = new Group();

      Manager manager = new Manager();
      Employee emp1 = new Employee();
      Employee emp2 = new Employee();

      manager.Name = "Zeus";
      manager.Level = 2;

      emp1.Name = "Ares";

      emp2.Name = "Artemis";

      Employee [] emps = new Employee[3]{manager, emp1, emp2};
      group.Employees = emps;

      s.Serialize(writer, group);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      FileStream fs = new FileStream(filename, FileMode.Open);
      XmlSerializer x = new XmlSerializer(typeof(Group));
      Group g = (Group) x.Deserialize(fs);
      Console.Write("Members:");

      foreach(Employee e in g.Employees)
      {
         Console.WriteLine("\t" + e.Name);
      }
   }
}

Applies to

Prodotto Versioni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0