System.Xml.Serialization.XmlArrayItemAttribute Class

Assembly: System.Xml.dll
Namespace: System.Xml.Serialization
Summary
Specifies the derived types that the XmlSerializer can place in a serialized array.
C# Syntax:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlArrayItemAttribute : Attribute
Remarks
The XmlArrayItemAttribute belongs to a family of attributes that controls how the XmlSerializer serializes, or deserializes, an object. For a complete list of similar attributes, see the conceptual topic at MSDN: attributesthatcontrolserialization.

You can apply the XmlArrayItemAttribute to any public read/write member that returns an array, or provides access to one (for example, a field that returns an array of objects, a collection, an ArrayList, or any class that implements the IEnumerable interface).

The XmlArrayItemAttribute supports polymorphism--in other words, it allows the XmlSerializer to add derived objects to an array. For example, suppose a class named Mammal is derived from a base class named Animal . Further suppose that a class named MyAnimals contains a field that returns an array of Animal objects. To allow the XmlSerializer to serialize both the Animal and Mammal type, apply the XmlArrayItemAttribute to the field twice, each time specifying one of the two acceptable types.



Note You can apply multiple instances of the XmlArrayItemAttribute or XmlElementAttribute to specify types of objects that can be inserted into the array.

Note The serialization of a field or property that returns an interface or array of interfaces is not supported.

For more information about using attributes, see the conceptual topic at MSDN: extendingmetadatausingattributes.



Note In your code, you can use the word XmlArrayItem instead of the longer XmlArrayItemAttribute.
Example
The following example serializes a class named Group , which contains a field named Employees that returns an array of Employee objects. The example applies the XmlArrayItemAttribute to the field, thereby instructing the XmlSerializer that it can insert objects of both the base class ( Employee ) type and derived class type ( Manager ) into the serialized array.
using System;
using System.IO;
using System.Xml.Serialization;

public class Group
{  
   /* The XmlArrayItemAttribute allows the XmlSerializer to insert
      both the base type (Employee) and derived type (Manager) 
      into serialized arrays. */

   [XmlArrayItem(typeof(Manager)),
   XmlArrayItem(typeof(Employee))]
   public Employee[] Employees;

   /* Use the XmlArrayItemAttribute to specify types allowed
      in an array of Object items. */
   [XmlArray]
   [XmlArrayItem (typeof(int),
   ElementName = "MyNumber"),
   XmlArrayItem (typeof(string),
   ElementName = "MyString"),
   XmlArrayItem(typeof(Manager))]
   public object [] ExtraInfo;
}   

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("TypeDoc.xml");
      test.DeserializeObject("TypeDoc.xml");
   }


   public void SerializeObject(string filename)
   {
      // Create a new XmlSerializer instance.
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // Writing the XML file to disk requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);
      Group group = new Group();
      
      Manager manager = new Manager();
      Employee emp1 = new Employee();
      Employee emp2 = new Employee();
      manager.Name = "Consuela";
      manager.Level = 3;
      emp1.Name = "Seiko";
      emp2.Name = "Martina";
      Employee [] emps = new Employee[3]{manager, emp1, emp2};
      group.Employees = emps;

      // Create an int and a string and assign to ExtraInfo.
      group.ExtraInfo = new Object[3]{43, "Extra", manager};

      // Serialize the object, and close the StreamWriter.
      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.WriteLine("Members:");
      
      foreach(Employee e in g.Employees) 
      {
         Console.WriteLine("\t" + e.Name);
      }
   }
}
   

    
See also:
System.Xml.Serialization Namespace | XmlArrayAttribute | XmlSerializer | XmlAttributes.XmlArrayItems | XmlAttributeOverrides | XmlAttributes | MSDN: introducingxmlserialization | MSDN: overridingserializationofclasseswithxmlattributeoverridesclass | XmlAttributes | MSDN: controllingserializationbyxmlserializerwithattributes | MSDN: anexampleofxmlserializationwithxmlserializer

System.Xml.Serialization.XmlArrayItemAttribute Member List:

Public Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the XmlArrayItemAttribute class.
ctor #2 Overloaded:
.ctor(string elementName)

Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document.
ctor #3 Overloaded:
.ctor(Type type)

Initializes a new instance of the XmlArrayItemAttribute class; specifies the Type that can be inserted into the serialized array.
ctor #4 Overloaded:
.ctor(string elementName, Type type)

Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document, and the Type that can be inserted into the generated XML document.
Public Properties
DataType Read-write

Gets or sets the XML data type of the generated XML element.
ElementName Read-write

Gets or sets the name of the generated XML element.
Form Read-write

Gets or sets a value indicating whether the name of the generated XML element is qualified.
IsNullable Read-write

Gets or sets a value indicating whether the XmlSerializer should serialize a member as an empty XML tag with the xsi:nil attribute set to true.
Namespace Read-write

Gets or sets the namespace of the generated XML element.
NestingLevel Read-write

Gets or sets the level in a hierarchy of XML elements that the XmlArrayItemAttribute affects.
Type Read-write

Gets or sets the type allowed in an array.
TypeId
(inherited from System.Attribute)
Read-only

See base class member description: System.Attribute.TypeId


When implemented in a derived class, gets a unique identifier for this Attribute.
Public Methods
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetHashCode
(inherited from System.Attribute)
See base class member description: System.Attribute.GetHashCode


Returns the hash code for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
IsDefaultAttribute
(inherited from System.Attribute)
See base class member description: System.Attribute.IsDefaultAttribute


When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match
(inherited from System.Attribute)
See base class member description: System.Attribute.Match


When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.Serialization.XmlArrayItemAttribute Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the XmlArrayItemAttribute class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlArrayItemAttribute();
Example
The following serializes a class named Transportation which contains a field named MyVehicles that returns an array of Vehicle objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the Car class, which is derived from the Vehicle class, into the array.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
 
public class Vehicle
{
   public string id;
}
public class Car:Vehicle
{
   public string Maker;   
}
 
public class Transportation
{  
   [XmlArrayItem(), 
   XmlArrayItem(typeof(Car), ElementName = "Automobile")]
   public Vehicle[] MyVehicles;
}
 
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("XmlArrayItem1.xml");
      test.DeserializeObject("XmlArrayItem1.xml");
   }

   private void SerializeObject(string filename){
      // Create an XmlSerializer for the Transportation class. 
      XmlSerializer MySerializer = new XmlSerializer(typeof(Transportation));
   
      // Writing the XML file to disk requires a TextWriter.
      TextWriter myTextWriter = new StreamWriter(filename);

      // Create the object to serialize.
      Transportation myTransportation = new Transportation();

      // Create objects to add to the array.
      Vehicle myVehicle= new Vehicle() ;
      myVehicle.id = "A12345";

      Car myCar = new Car();
      myCar.id = "Car 34";
      myCar.Maker = "FamousCarMaker";

      myTransportation.MyVehicles = 
      new Vehicle[2] {myVehicle, myCar};
      
      // Serialize the object, and close the StreamWriter.
      MySerializer.Serialize(myTextWriter, myTransportation);
      myTextWriter.Close();
   }
 
   private void DeserializeObject(string filename)
   {
      // Create an XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer(typeof(Transportation));
      FileStream myFileStream = new FileStream(filename,FileMode.Open);
      Transportation myTransportation =
      (Transportation) mySerializer.Deserialize(myFileStream);
 
      for(int i = 0; i < myTransportation.MyVehicles.Length;i++)
      {
         Console.WriteLine(myTransportation.MyVehicles[i].id);
      }
   }
 }

    

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document.
C# Syntax:
public XmlArrayItemAttribute(
   string elementName
);
Parameters:

elementName

The name of the XML element.

Remarks
This overload sets the XmlArrayItemAttribute.ElementName property.

Use this overload if you want the name of the generated XML element to differ from the member's identifier.

An XML document that includes namespaces can contain more than one version of an element name. For details, see the XmlArrayItemAttribute.ElementName property.

Example
The following example serializes a class named Transportation which contains a field named MyVehicles that returns an array of Vehicle objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the Car class, which is derived from the Vehicle class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.ElementName property using the elementName parameter.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
 
public class Vehicle
{
   public string id;
}
public class Car:Vehicle
{
   public string Maker;
}
 
public class Transportation
{  
   [XmlArrayItem(ElementName = "Transportation"), 
   XmlArrayItem(typeof(Car), ElementName = "Automobile")]
   public Vehicle[] MyVehicles;
}
 
public class Run
{
   public static void Main()
   {
      Run test= new Run();
      test.SerializeObject("XmlArrayItem2.xml");
      test.DeserializeObject("XmlArrayItem2.xml");
   }
 
   private void SerializeObject(string filename)
   {
      // Create an XmlSerializer object for the Transportation class.
      XmlSerializer MySerializer = 
      new XmlSerializer(typeof(Transportation));

      // Writing the XML file to disk requires a TextWriter.
      TextWriter myTextWriter = new StreamWriter(filename);
 
      Transportation myTransportation = new Transportation();

      Vehicle myVehicle= new Vehicle() ;
      myVehicle.id = "A12345";

      Car myCar = new Car();
      myCar.id = "Car 34";
      myCar.Maker = "FamousCarMaker";
       
      Vehicle [] myVehicles = {myVehicle, myCar};
      myTransportation.MyVehicles = myVehicles;

      // Serialize the object, and close the StreamWriter.
      MySerializer.Serialize(myTextWriter, myTransportation);
      myTextWriter.Close();
   }
 
   private void DeserializeObject(string filename)
   {
      // Create the serializer with the type to deserialize.
      XmlSerializer mySerializer = 
      new XmlSerializer(typeof(Transportation));
      FileStream myFileStream = new FileStream(filename,FileMode.Open);
      Transportation myTransportation =
      (Transportation) mySerializer.Deserialize(myFileStream);
 
      for(int i = 0;i < myTransportation.MyVehicles.Length;i++)
      {
         Console.WriteLine(myTransportation.MyVehicles[i].id);
      }
   }
}
   

    

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the XmlArrayItemAttribute class; specifies the Type that can be inserted into the serialized array.
C# Syntax:
public XmlArrayItemAttribute(
   Type type
);
Parameters:

type

The Type of the object to serialize.

Example
The following example serializes a class named Transportation which contains a field named MyVehicles that returns an array of Vehicle objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the Car class, which is derived from the Vehicle class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.Type property using the type parameter.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
 
public class Vehicle
{
   public string id;
}
public class Car:Vehicle
{
   public string Maker;
}
 
public class Transportation
{  
   [XmlArrayItem(typeof(Vehicle)), 
   XmlArrayItem(typeof(Car))]
   public Vehicle[] MyVehicles;
}
 
public class Run
{
   public static void Main()
   {
      Run test= new Run();
      test.SerializeObject("XmlArrayItem3.xml");
      test.DeserializeObject("XmlArrayItem3.xml");
   }
 
   private void SerializeObject(string filename)
   {
       // Create an XmlSerializer object. 
      XmlSerializer MySerializer = 
      new XmlSerializer(typeof(Transportation));
      
      // Writing the XML file to disk requires a TextWriter.
      TextWriter myTextWriter = new StreamWriter(filename);
 
      Transportation myTransportation = new Transportation();

      Vehicle myVehicle= new Vehicle() ;
      myVehicle.id = "A12345";

      Car myCar = new Car();
      myCar.id = "Car 34";
      myCar.Maker = "FamousCarMaker";
       
      Vehicle [] myVehicles = {myVehicle, myCar};
      myTransportation.MyVehicles = myVehicles;

      // Serialize the object, and close the StreamWriter.
      MySerializer.Serialize(myTextWriter, myTransportation);
      myTextWriter.Close();
   }
 
   private void DeserializeObject(string filename)
   {
      // Create the serializer with the type to deserialize.
      XmlSerializer mySerializer = 
      new XmlSerializer(typeof(Transportation));
      FileStream myFileStream = new FileStream(filename,FileMode.Open);
      Transportation myTransportation =
      (Transportation) mySerializer.Deserialize(myFileStream);
 
      for(int i = 0;i < myTransportation.MyVehicles.Length;i++)
      {
         Console.WriteLine(myTransportation.MyVehicles[i].id);
      }
   }
}
   

    

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document, and the Type that can be inserted into the generated XML document.
C# Syntax:
public XmlArrayItemAttribute(
   string elementName,
   Type type
);
Parameters:

elementName

The name of the XML element.

type

The Type of the object to serialize.

Remarks
This overload sets the XmlArrayItemAttribute.ElementName and the XmlArrayItemAttribute.Type properties.

Use this overload if you want the name of the generated XML element to differ from the member's identifier.

An XML document that includes namespaces can contain more than one version of an element name. For details, see the XmlArrayItemAttribute.ElementName property.

Example
The following example serializes a class named Transportation which contains a field named MyVehicles that returns an array of Vehicle objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the Car class, which is derived from the Vehicle class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.ElementName property using the elementName parameter, and the XmlArrayItemAttribute.Type property using the type parameter.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
 
public class Vehicle
{
   public string id;
}
public class Car:Vehicle
{
   public string Maker;
}
 
public class Transportation
{  
   [XmlArray]
   [XmlArrayItem("Transport", typeof(Vehicle)), 
   XmlArrayItem("Automobile", typeof(Car))]
   public Vehicle[] MyVehicles;
}
 
public class Run
{
   public static void Main()
   {
      Run test= new Run();
      test.SerializeObject("XmlArrayItem4.xml");
      test.DeserializeObject("XmlArrayItem4.xml");
   }
 
   private void SerializeObject(string filename)
   {
       // Create an XmlSerializer object for the Transportation class.
      XmlSerializer MySerializer = 
      new XmlSerializer(typeof(Transportation));

      // Writing the XML file to disk requires a TextWriter.
      TextWriter myTextWriter = new StreamWriter(filename);
 
      Transportation myTransportation = new Transportation();

      Vehicle myVehicle= new Vehicle() ;
      myVehicle.id = "A12345";

      Car myCar = new Car();
      myCar.id = "Car 34";
      myCar.Maker = "FamousCarMaker";
       
      Vehicle [] myVehicles = {myVehicle, myCar};
      myTransportation.MyVehicles = myVehicles;

      // Serialize the object, and close the StreamWriter.
      MySerializer.Serialize(myTextWriter, myTransportation);
      myTextWriter.Close();
   }
 
   private void DeserializeObject(string filename)
   {
      // Create an XmlSerializer object.
      XmlSerializer mySerializer = 
      new XmlSerializer(typeof(Transportation));
      FileStream myFileStream = new FileStream(filename,FileMode.Open);
      Transportation myTransportation =
      (Transportation) mySerializer.Deserialize(myFileStream);
 
      for(int i = 0;i < myTransportation.MyVehicles.Length;i++)
      {
         Console.WriteLine(myTransportation.MyVehicles[i].id);
      }
   }
}
   

    

Return to top


Property: DataType (read-write)
Summary
Gets or sets the XML data type of the generated XML element.
C# Syntax:
public string DataType {get; set;}
Remarks
The following table lists the XML Schema simple data types with their .NET equivalents.

For the XML Schema base64Binary and hexBinary data types, use an array of Byte structures, and apply a XmlArrayItemAttribute with the XmlArrayItemAttribute.DataType property set to "base64Binary" or "hexBinary", as appropriate. For the XML Schema time and date data types, use the DateTime type and apply the XmlArrayItemAttribute with the XmlArrayItemAttribute.DataType set to "date" or "time".

For every XML Schema type that is mapped to a string, apply the XmlArrayItemAttribute with its XmlArrayItemAttribute.DataType property set to the XML Schema type. However, this will not change the serialization format, only the schema for the member.



Note The property is case-sensitive, so you must set it exactly to one of the XML Schema data types.

Note Passing binary data as an XML element is more efficient then passing it as an XML attribute.

For more information about XML Schema data types, see the World Wide Web Consortium (www.w3.org ) document "XML Schema Part 2: Datatypes".



XSD data type .NET data type
anyURI String
base64Binary Array of Byte objects
boolean Boolean
byte SByte
date DateTime
dateTime DateTime
decimal Decimal
double Double
ENTITY String
ENTITIES String
float Single
gDay String
gMonth String
gMonthDay String
gYear String
gYearMonth String
hexBinary Array of Byte objects
ID String
IDREF String
IDREFS String
int Int32
integer String
language String
long Int64
Name String
NCName String
negativeInteger String
NMTOKEN String
NMTOKENS String
normalizedString String
nonNegativeInteger String
nonPositiveInteger String
NOTATION String
positiveInteger String
QName XmlQualifiedName
recurringDate String
duration String
string String
short Int16
time DateTime
token String
unsignedByte Byte
unsignedInt UInt32
unsignedLong UInt64
unsignedShort UInt16
Example
The following example serializes a class named PurchaseOrder . Several instances of the XmlArrayItemAttribute class are applied to three members, and the XmlArrayItemAttribute.DataType property for each instance is set to a type allowed in the array.
using System;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Xml.Schema;
public class PurchaseOrder
{
   [XmlArrayItem(DataType = "gMonth", 
   ElementName="MyMonths",
   Namespace = "http://www.cohowinery.com")]
   public string[] Months;

   [XmlArrayItem(typeof(Item)), XmlArrayItem(typeof(NewItem))]
   public Item[] Items;

   [XmlArray(IsNullable = true)]
   [XmlArrayItem(typeof(string)), 
   XmlArrayItem(typeof(double)), 
   XmlArrayItem(typeof(NewItem))]
   public object[] Things;
   }

public class Item{
   public string ItemID;
   public Item(){}
   public Item(string id){
   	ItemID = id;
   }
}
public class NewItem:Item{
   public string Category;
   public NewItem(){}
   public NewItem(string id, string cat){
   	this.ItemID = id;
   	Category = cat;
   	}
}
 
public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.SerializeObject("ArrayItemEx.xml");
      t.DeserializeObject("ArrayItemEx.xml");
   } 

   private void SerializeObject(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer = 
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      // Create a PurchaseOrder and set its properties.
      PurchaseOrder po=new PurchaseOrder();
      po.Months = new string[]{ "March", "May", "August"};
      po.Items= new Item[]{new Item("a1"), new NewItem("b1", "book")};
      po.Things= new object[] {"String", 2003.31, new NewItem("xxx", "book")};
      
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }
 
   protected void DeserializeObject(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
   
      // A FileStream is needed to read the XML document.
      FileStream fs = new FileStream(filename, FileMode.Open);
      // Declare an object variable of the type to be deserialized.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      foreach(string s in po.Months)
      	  Console.WriteLine(s);
      foreach(Item i in po.Items)
         Console.WriteLine(i.ItemID);
      foreach(object thing in po.Things)
         Console.WriteLine(thing); 
   } 
}


    

Return to top


Property: ElementName (read-write)
Summary
Gets or sets the name of the generated XML element.
C# Syntax:
public string ElementName {get; set;}
Remarks
Specify an XmlArrayItemAttribute.ElementName if you want the name of the generated XML element to differ from the member's identifier.

You can set the same XmlArrayAttribute.ElementName value to more than one class member, if the generated XML document uses XML namespaces to distinguish between identically named members. For details on how to use namespaces and prefixed names in the XML document, see the XmlSerializerNamespaces class.

Example
The following example sets the XmlArrayItemAttribute.ElementName property for the Vehicle and Car class--thereby changing the names of XML elements that the XmlSerializer generates for those classes.
public class Transportation
{  
   [XmlArray("Vehicles")]
   /* Specify acceptable types and the ElementName generated 
      for each object type. */
   [XmlArrayItem(typeof(Vehicle), ElementName = "Transport"), 
   XmlArrayItem(typeof(Car), ElementName = "Automobile")]
   public Vehicle[] MyVehicles;
}

// By default, this class results in XML elements named "Vehicle". 
public class Vehicle
{
   public string id;
}

// By default, this class results in XML elements named "Car". 
public class Car:Vehicle
{
   public string Maker;
}


    

Return to top


Property: Form (read-write)
Summary
Gets or sets a value indicating whether the name of the generated XML element is qualified.
C# Syntax:
public XmlSchemaForm Form {get; set;}
Exceptions
Exception Type Condition
Exception The XmlArrayItemAttribute.Form property is set to XmlSchemaForm.Unqualified and a XmlArrayItemAttribute.Namespace value is specified.
Remarks
The XmlAttributeAttribute.Form property determines whether an XML element name is qualified, based on the World Wide Web Consortium (www.w3.org) specification "Namespaces in XML.

If the XmlAttributeAttribute.Namespace property is set to any value, attempting to set the XmlElementAttribute.Form property to XmlSchemaForm.Unqualified throws an exception.

The default value, XmlSchemaForm.None, instructs the XmlSerializer to check the schema for the XML document to determine whether the namespace is qualified. For elements, the XmlSerializer checks the value of the schema-element attribute elementFormDefault. For attributes, it checks the value of the schema-element attribute attributeFormDefault . For example, the following XML Schema indicates that the Name element is qualified, while the Number element is unqualified.

              <schema elementFormDefault="qualified" 
              attributeFormDefault="unqualified">
                 <element name="Name"/>
                 <attribute name="Number"/>
              </schema>
            
Example
The following example sets the XmlArrayItemAttribute.Form property for the Vehicle class to XmlSchemaForm.Unqualified, and the XmlArrayItemAttribute.Form property for the Car class to XmlSchemaForm.Qualified.
public class Transportation
{  
   [XmlArray("Vehicles")]
   // Specify the Form property value.
   [XmlArrayItem(typeof(Vehicle), 
   Form = XmlSchemaForm.Unqualified), 
   XmlArrayItem(typeof(Car), 
   Form = XmlSchemaForm.Qualified)]
   public Vehicle[] MyVehicles;
}

public class Vehicle
{
   public string id;
}

public class Car:Vehicle
{
   public string Maker;
}


    

Return to top


Property: IsNullable (read-write)
Summary
Gets or sets a value indicating whether the XmlSerializer should serialize a member as an empty XML tag with the xsi:nil attribute set to true.
C# Syntax:
public bool IsNullable {get; set;}
Remarks
The XML schema specification for structures allows an XML document to explicitly signal that an element's content is missing. Such an element contains the attribute xsi:nil set to true. For more information, see the World Wide Web Consortium (www.w3.org) specification titled "XML Schema Part 1: Structures".

If the XmlArrayItemAttribute.IsNullable property is true, the xsi:nil attribute is generated for class members that have been set to null. For example, if you set a field named MyStringArray to null, the XmlSerializer generates the following XML code.

              <MyStringArray xsi:nil = "true" />
            

If the XmlArrayItemAttribute.IsNullable property is false, no XML element is generated.



Note You cannot apply the XmlArrayItemAttribute.IsNullable property to a member typed as a value type because a value type cannot contain null.
Example
The following example serializes a class named Group , which contains a field named Employees that returns an array of Employee objects. A second class named Manager derives from Employee . An XmlArrayItemAttribute specifies that the XmlSerializer can insert both Employee and Manager objects into the array. The example sets the XmlArrayItemAttribute.IsNullable property, thereby telling the XmlSerializer not to generate the xsi:nil attribute objects in the array set to null.
using System;
using System.IO;
using System.Xml.Serialization;

public class Group
{   
   [XmlArray(IsNullable = true)]
   [XmlArrayItem(typeof(Manager), IsNullable = false),
   XmlArrayItem(typeof(Employee), IsNullable = false)]
   public Employee[] Employees;
}   

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("TypeDoc.xml");
   }

   public void SerializeObject(string filename)
   {
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      // Create the object to serialize.
      Group group = new Group();

      // Create a null Manager object.
      Manager mgr = null;
      
      // Create a null Employee object.
      Employee y = null;
      
      group.Employees = new Employee[2] {mgr, y};

      // Serialize the object and close the TextWriter.
      s.Serialize(writer, group);
      writer.Close();

   }
}


    

Return to top


Property: Namespace (read-write)
Summary
Gets or sets the namespace of the generated XML element.
C# Syntax:
public string Namespace {get; set;}
Remarks
The XmlArrayItemAttribute.Namespace property conforms to the World Wide Web Consortiuem (www.w3.org) specification "Namespaces in XML" .

To create namespaces to use in the XML document and associated prefixes, you must create an XmlSerializerNamespaces that contains all the prefix-namespace pairs. The namespace you set for each XmlArrayAttribute must be contained in the XmlSerializerNamespaces. When the XmlSerializer generates the document, it correctly prefixes the element name for each array item.

Example
The following example applies an XmlArrayItemAttribute and sets the XmlArrayItemAttribute.Namespace property.
public class Transportation
{  
   // Set the Namespace property.
   [XmlArrayItem(typeof(Car), Namespace = "http://www.cpandl.com")]
   public Vehicle[] MyVehicles;
}


    

Return to top


Property: NestingLevel (read-write)
Summary
Gets or sets the level in a hierarchy of XML elements that the XmlArrayItemAttribute affects.
C# Syntax:
public int NestingLevel {get; set;}
Remarks
An XML document can contain hierarchies of XML elements. To represent such a hierarchy, an array of arrays is used. In such an array, each index represents a level in the hierarchy. Therefore, the XmlArrayItemAttribute.NestingLevel property is only used when applying an XmlArrayItemAttribute to a field that returns an array of arrays.

When applying the attribute, specify which hierarchy level the attribute affects by setting the XmlArrayItemAttribute.NestingLevel. The first index always has the value of zero; therefore it is optional to set its XmlArrayItemAttribute.NestingLevel --an XmlArrayItemAttribute without a XmlArrayItemAttribute.NestingLevel value will be applied to the first array index. Only the subsequent XmlArrayItemAttribute objects need XmlArrayItemAttribute.NestingLevel values specified (as 1, 2, 3, and so forth).

Example
The following example applies three XmlArrayItemAttribute attributes to an array of arrays. To specify which of the arrays each attribute applies to, the XmlArrayItemAttribute.NestingLevel property is set to the index of the arrays.
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

public class Forest{
   /* Set the NestingLevel for each array. The first 
   attribute (NestingLevel = 0) is optional. */
   [XmlArrayItem(ElementName = "tree", NestingLevel = 0)]
   [XmlArrayItem(ElementName = "branch", NestingLevel = 1)]
   [XmlArrayItem(ElementName = "leaf",NestingLevel = 2)]
   public string[][][] TreeArray;
}

public class Test{
   public static void Main(){
      Test t = new Test();
      t.SerializeObject("Tree.xml");
   }
   private void SerializeObject(string filename){
      XmlSerializer serializer = 
      new XmlSerializer(typeof(Forest));

      Forest f = new Forest();
      string[][][] myTreeArray = new string[2] [][];

      string[][]myBranchArray1= new string[1][];
      myBranchArray1[0]=new string[1]{"One"};
      myTreeArray[0]=myBranchArray1;

      string[][]myBranchArray2= new string[2][];
      myBranchArray2[0]=new string[2]{"One","Two"};
      myBranchArray2[1]=new string[3]{"One","Two","Three"};
      myTreeArray[1]=myBranchArray2;
   
      f.TreeArray=myTreeArray;

     serializer.Serialize(Console.Out, f);
   }
}

    

Return to top


Property: Type (read-write)
Summary
Gets or sets the type allowed in an array.
C# Syntax:
public Type Type {get; set;}
Remarks
Use the XmlElementAttribute.Type property to specify an overridden type for a public field or public read/write property value.

If a field or property returns an array of type Object, apply multiple instances of the XmlArrayItemAttribute to the field or property. For each instance, set the XmlElementAttribute.Type property to a type of object that can be inserted into the array.

If an array contains only primitive types, you need not apply the XmlArrayItemAttribute. By default, the XmlSerializer will generate a series of elements, each with the same element name, for each value, but the type of each element will be set to the XML Schema data type. For example, the following code:

              ' Visual Basic code
              Public Class Arrays
                 Public XSDTypes ()As Object= New Object(){"one", 2, 3.0}
              End Class
              // C# code
              public class MyArray{
                 // No XmlArrayItemAttribute is applied. 
                 public object[] XSDTypes= new object[]{"one", 2, 3.2};
              }
            

will result in this XML:

              <?xml version="1.0" encoding="utf-8"?>
              <Arrays xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <XSDTypes>
                  <Object xsi:type="xsd:string">one</Object>
                  <Object xsi:type="xsd:int">2</Object>
                  <Object xsi:type="xsd:double">3</Object>
                </XSDTypes>
              </Arrays>
            

However, if you specify the XmlArrayItemAttribute.Type property for each primitive type, the element name for each value will be generated using the .NET type name. For example this code:

              ' Visual Basic code
              Public Class Arrays
                 <XmlArrayItem(GetType(String)), _
                 XmlArrayItem(GetType(Integer)), _
                 XmlArrayItem(GetType(Double))> _
                 Public PrimitiveTypes () As Object = New Object(){"one", 2, 3.0}
              End Class
              // C# code
              public class Arrays{
                 [XmlArrayItem(typeof(string))]
                 [XmlArrayItem(typeof(int))]
                 [XmlArrayItem(typeof(double))]
                 public object [] PrimitiveTypes = new object[]{"one", 2, 3.0};
              }
            

will result in this XML:

              <?xml version="1.0" encoding="utf-8"?>
              <Arrays xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <PrimitiveTypes>
                  <string>one</string>
                  <int>2</int>
                  <double>3</double>
                </PrimitiveTypes>
              </Arrays>
            
Example
The following example serializes an array of objects. The field that returns the array is attributed with two XmlArrayItemAttribute instances. Each instance instructs the XmlSerializer to accept the specified XmlArrayItemAttribute.Type in the array.
using System;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* The Type property instructs the XmlSerializer to accept both
   the Person and Manager types in the array. */
   [XmlArrayItem(Type = typeof(Manager)),
   XmlArrayItem(Type=typeof(Person))]
   public Person[]Staff;
}

public class Person
{
   public string Name;
}

public class Manager:Person
{
   public int Rank;
}

public class Run 
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeOrder("TypeEx.xml");
   }


   public void SerializeOrder(string filename)
   {
      // Create an XmlSerializer instance.
      XmlSerializer xSer = 
      new XmlSerializer(typeof(Group));

      // Create the Group object, and two array items.
      Group myGroup = new Group();

      Person p1 = new Person();
      p1.Name = "Jacki";
      Manager p2 = new Manager();

      p2.Name = "Megan";
      p2.Rank = 2;

      Person [] myStaff = {p1,p2};
      myGroup.Staff = myStaff;

      // Serialize the object, and close the StreamWriter.
      TextWriter writer = new StreamWriter(filename);
      xSer.Serialize(writer, myGroup);
   }
}

    

Return to top


Property: TypeId (read-only)
Inherited
See base class member description: System.Attribute.TypeId

Summary
When implemented in a derived class, gets a unique identifier for this Attribute.
C# Syntax:
public virtual object TypeId {get;}
Remarks
As implemented, this identifier is merely the Type of the attribute. However, it is intended that the unique identifier be used to identify two attributes of the same type.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlArrayItemAttribute();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Attribute.GetHashCode

Summary
Returns the hash code for this instance.
C# Syntax:
public override int GetHashCode();
Return Value:
A 32-bit signed integer hash code.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: IsDefaultAttribute()
Inherited
See base class member description: System.Attribute.IsDefaultAttribute

Summary
When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
C# Syntax:
public virtual bool IsDefaultAttribute();
Return Value:
true if this instance is the default attribute for the class; otherwise, false.
Remarks
The default implementation of this class returns false, and must be implemented in the derived class to be useful to that class.

The implementation of this method in a derived class compares the value of this instance to a standard, default value obtained by some means, then returns a Boolean value that indicates whether the value of this instance is equal to the standard. The standard value is typically coded as a constant in the implementation, or stored programmatically in a field used by the implementation.

Return to top


Method: Match(
   object obj
)
Inherited
See base class member description: System.Attribute.Match

Summary
When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
C# Syntax:
public virtual bool Match(
   object obj
);
Parameters:

obj

An Object to compare with this instance of Attribute.

Return Value:
true if this instance equals obj; otherwise, false.
Remarks
This method determines if one Attribute equals another. Its default implementation is the same as Attribute.Equals, which performs a value and reference comparison. Override this method to implement support for attribute values, such as flags or bitfields, that consist of components that are meaningful in themselves. For example, consider an attribute whose value is a binary field divided into a bitfield of flags. Two instances of this attribute have one flag in set in common while all the other flags differ. The Equal method cannot determine that the two instances have the same flag set, but the Match method can.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.