System.Xml.Serialization.XmlElementAttribute Class

Assembly: System.Xml.dll
Namespace: System.Xml.Serialization
Summary
Indicates that a public field or property represents an XML element when the XmlSerializer serializes or deserializes the containing object.
C# Syntax:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlElementAttribute : Attribute
Remarks
The XmlElementAttribute 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.

An XML document usually contains XML elements, each of which consists of three parts: an opening tag with possible attributes, a closing tag, and the data between the tags. XML tags can be nested--that is, the data between tags can also be XML elements. This capacity of one element to enclose another allows the document to contain hierarchies of data. An XML element can also include attributes.

Apply the XmlElementAttribute to public fields or public read/write properties to control characteristics of the XML elements such as the element name and namespace.

The XmlElementAttribute can be applied multiple times to a field that returns an array of objects. The purpose of this is to specify (through the XmlElementAttribute.Type property) different types that can be inserted into the array. For example, the array in the C# code below accepts both strings and integers.

          public class Things{
             [XmlElement(DataType = typeof(string)),
             XmlElement(DataType = typeof(int))]
             public object[] StringsAndInts;
          }
        

This results in XML that might resemble the following.

          <Things>
             <string>Hello</string>
             <int>999</int>
             <string>World</string>
          </Things>
        

Note that when you apply the XmlElementAttribute multiple times without specifying an XmlElementAttribute.ElementName property value, the elements are named after the type of the acceptable objects.

If you apply the XmlElementAttribute to a field or property that returns an array, the items in the array are encoded as a sequence of XML elements.

In contrast, if an XmlElementAttribute is not applied to such a field or property, the items in the array are encoded as a sequence of elements, nested under an element named after the field or property. (Use the XmlArrayAttribute and XmlArrayItemAttribute attributes to control how an array is serialized.)

You can set the XmlElementAttribute.Type property to specify a type that is derived from the type of the original field or property--that is, the field or property to which you have applied the XmlElementAttribute.

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

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



Note In your code, you can use the word XmlElement instead of the longer XmlElementAttribute.
Example
The following example serializes a class named Group and applies the XmlElementAttribute to several of its members. The field named Employees returns an array of Employee objects. In this case, the XmlElementAttribute specifies that that the resulting XML should not be nested (which is the default behavior of items in an array).
using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Set the element name and namespace of the XML element.
   By applying an XmlElementAttribute to an array,  you instruct
   the XmlSerializer to serialize the array as a series of XML
   elements, instead of a nested set of elements. */
   
   [XmlElement(
   ElementName = "Members",
   Namespace = "http://www.cpandl.com")]
   public Employee[] Employees;
      
   [XmlElement(DataType = "double",
   ElementName = "Building")]
   public double GroupID;

   [XmlElement(DataType = "hexBinary")]
   public byte [] HexBytes;


   [XmlElement(DataType = "boolean")]
   public bool IsActive;

   [XmlElement(Type = typeof(Manager))]
   public Employee Manager;

   [XmlElement(typeof(int),
   ElementName = "ObjectNumber"),
   XmlElement(typeof(string),
   ElementName = "ObjectString")]
   public ArrayList 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("FirstDoc.xml");
       test.DeserializeObject("FirstDoc.xml");
    }


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

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

      /* Create an instance of the group to serialize, and set
         its properties. */
      Group group = new Group();
      group.GroupID = 10.089f;
      group.IsActive = false;
      
      group.HexBytes = new byte[1]{Convert.ToByte(100)};

      Employee x = new Employee();
      Employee y = new Employee();

      x.Name = "Jack";
      y.Name = "Jill";
      
      group.Employees = new Employee[2]{x,y};

      Manager mgr = new Manager();
      mgr.Name = "Sara";
      mgr.Level = 4;
      group.Manager = mgr;

      /* Add a number and a string to the 
      ArrayList returned by the ExtraInfo property. */
      group.ExtraInfo = new ArrayList();
      group.ExtraInfo.Add(42);
      group.ExtraInfo.Add("Answer");

      // Serialize the object, and close the TextWriter.      
      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(g.Manager.Name);
      Console.WriteLine(g.GroupID);
      Console.WriteLine(g.HexBytes[0]);
      foreach(Employee e in g.Employees)
      {
         Console.WriteLine(e.Name);
      }
   }
}
   

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

System.Xml.Serialization.XmlElementAttribute 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 XmlElementAttribute class.
ctor #2 Overloaded:
.ctor(string elementName)

Initializes a new instance of the XmlElementAttribute class and specifies the name of the XML element.
ctor #3 Overloaded:
.ctor(Type type)

Initializes a new instance of the XmlElementAttribute class and specifies a type for the member to which the XmlElementAttribute is applied, which is used by the XmlSerializer when serializing or deserializing a containing object.
ctor #4 Overloaded:
.ctor(string elementName, Type type)

Initializes a new instance of the XmlElementAttribute; specifies the name of the XML element and a derived type for the member to which the XmlElementAttribute is applied, which is used when the XmlSerializer serializes a containing object.
Public Properties
DataType Read-write

Gets or sets the XML Schema definition (XSD) data type of the XMl element generated by the XmlSerializer.
ElementName Read-write

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

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

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

Gets or sets the namespace assigned to the XML element that results when the class is serialized.
Type Read-write

Gets or sets the object type used to represent the XML element.
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.XmlElementAttribute Member Details

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

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlElementAttribute();
Example
The following example applies the XmlElementAttribute a class.
public class MyClass
{
   [XmlElement()]
   public string TeacherName;
}


    

Return to top


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

elementName

The XML element name of the serialized member.

Remarks
By default, the XmlSerializer uses the member name as the XML element name when serializing a class instance. For example, a field named Vehicle generates an XML element named Vehicle. However, if you need a different element, such as Cars , pass it in the elementName parameter.
Example
The following example shows a simple class that contains a single field named Vehicles . The example applies the XmlElementAttribute to the field and includes the elementName parameter, thereby instructing the XmlSerializer to generate XML elements named "Cars" rather than "Vehicles".
public class Transportation
{
   [XmlElement("Cars")]
   public string Vehicles;
}


    

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the XmlElementAttribute class and specifies a type for the member to which the XmlElementAttribute is applied, which is used by the XmlSerializer when serializing or deserializing a containing object.
C# Syntax:
public XmlElementAttribute(
   Type type
);
Parameters:

type

The Type of an object derived from the member's type.

Remarks
Use the type parameter to specify a type that is derived from a base class. For example, suppose a property named MyAnimal returns an Animal object. You want to enhance the object, so you create a new class named Mammal that inherits from the Animal class. To instruct the XmlSerializer to accept the Mammal class when it serializes the MyAnimal property, pass the Type of the Mammal class to the constructor.
Example
The following example serializes a class named Orchestra that contains a single field named Instruments , which returns an array of Instrument objects. A second class named Brass inherits from the Instrument class. The example applies the XmlElementAttribute to the Instruments field, and specifies the Brass type, allowing the Instruments field to accept Brass objects. The example also specifies the name of the XML element by setting the XmlElementAttribute.ElementName property.
using System;
using System.IO;
using System.Xml.Serialization;

public class Orchestra
{
   public Instrument[] Instruments;
}   

public class Instrument
{
   public string Name;
}

public class Brass:Instrument{
   public bool IsValved;
}

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

    public void SerializeObject(string filename)
    {
      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);
      
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that overrides the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Creates the object to serialize.
      Orchestra band = new Orchestra();
      
      // Creates an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that override the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* Deserializing differs from serializing. To read the 
         derived-object values, declare an object of the derived 
         type (Brass) and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments) 
      {
         b= (Brass)i;
         Console.WriteLine(
         b.Name + "\n" + 
         b.IsValved);
      }
   }
}


    

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the XmlElementAttribute; specifies the name of the XML element and a derived type for the member to which the XmlElementAttribute is applied, which is used when the XmlSerializer serializes a containing object.
C# Syntax:
public XmlElementAttribute(
   string elementName,
   Type type
);
Parameters:

elementName

The XML element name of the serialized member.

type

The Type of an object derived from the member's type.

Remarks
By default, the XmlSerializer uses the member name as the XML element name when serializing a class instance. For example, a field named Vehicle generates an XML element named Vehicle. However, if you need a different element, such as Cars, pass it in the elementName parameter.

Use the type parameter to specify a type that is derived from a base class. For example, suppose a property named MyAnimal returns an Animal object. You want to enhance the object, so you create a new class named Mammal that inherits from the Animal class. To instruct the XmlSerializer to accept the Mammal class when it serializes the MyAnimal property, pass the Type of the Mammal class to the constructor.

Example
The following example serializes a class named Orchestra that contains a single field named Instruments , which returns an array of Instrument objects. A second class named Brass inherits from the Instrument class. The example applies the XmlElementAttribute to the Instruments field, and specifies the Brass type, allowing the Instruments field to accept Brass objects. The example also specifies the name of the XML element by setting the XmlElementAttribute.ElementName property.
using System;
using System.IO;
using System.Xml.Serialization;

public class Orchestra
{
   public Instrument[] Instruments;
}   

public class Instrument
{
   public string Name;
}

public class Brass:Instrument{
   public bool IsValved;
}

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

    public void SerializeObject(string filename)
    {
      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);
      
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that overrides the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Creates the object to serialize.
      Orchestra band = new Orchestra();
      
      // Creates an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that override the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* Deserializing differs from serializing. To read the 
         derived-object values, declare an object of the derived 
         type (Brass) and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments) 
      {
         b= (Brass)i;
         Console.WriteLine(
         b.Name + "\n" + 
         b.IsValved);
      }
   }
}


    

Return to top


Property: DataType (read-write)
Summary
Gets or sets the XML Schema definition (XSD) data type of the XMl element generated by the XmlSerializer.
C# Syntax:
public string DataType {get; set;}
Exceptions
Exception Type Condition
Exception The XML Schema data type you've specified cannot be mapped to the .NET data type.
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 XmlElementAttribute with the XmlElementAttribute.DataType set to "base64Binary" or "hexBinary", as appropriate. For the XML Schema time and date data types, use the DateTime type and apply the XmlElementAttribute with the XmlElementAttribute.DataType set to "date" or "time".

For every XML Schema type that is mapped to a string, apply the XmlElementAttribute with its XmlElementAttribute.DataType property set to the XML Schema type. Not that 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 Schema attribute.

For more information about XML data types, see the World Wide Web Consortium (www.w3.org) document named "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 Group that contains a field named ExtraInfo, which returns an ArrayList. The example applies two instances of the XmlElementAttribute to the field, specifying different XmlElementAttribute.DataType values for each instance. Each instance enables the XmlSerializer serialize the specified types inserted into the array.
using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Apply two XmlElementAttributes to the field. Set the DataType
      to string an int to allow the ArrayList to accept 
      both types. The Namespace is also set to different values
      for each type. */ 
   [XmlElement(DataType = "string",
   Type = typeof(string),
   Namespace = "http://www.cpandl.com"),
   XmlElement(DataType = "int", 
   Namespace = "http://www.cohowinery.com",
   Type = typeof(int))]
   public ArrayList ExtraInfo;
}

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

    public void SerializeObject(string filename)
    {
      // A TextWriter is needed to write the file.
      TextWriter writer = new StreamWriter(filename);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Group));

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

      /* Add a string and an integer to the ArrayList returned
         by the ExtraInfo field. */
      myGroup.ExtraInfo = new ArrayList();
      myGroup.ExtraInfo.Add("hello");
      myGroup.ExtraInfo.Add(100);

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


    

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 the 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 XmlElementAttribute.ElementName property of an XmlElementAttribute to a new value.
// This is the class that will be serialized.
public class XClass
{
   /* The XML element name will be XName
   instead of the default ClassName. */
   [XmlElement(ElementName = "XName")]
   public string ClassName;
} 

    
See also:
XmlAttributeAttribute.AttributeName

Return to top


Property: Form (read-write)
Summary
Gets or sets a value indicating whether the element is qualified.
C# Syntax:
public XmlSchemaForm Form {get; set;}
Remarks
The XmlAttributeAttribute.Form property determines whether an XML element is qualified or unqualified. The XmlAttributeAttribute.Form property conforms to the World Wide Web Consortium (www.w3.org) 1999 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 setting, XmlSchemaForm.None, instructs the XmlSerializer to check the schema for the XML document to determine whether the namespace is qualified. If the schema does not specify a value for an individual element or attribute, the XmlSerializer uses the elementFormDefault and attributeFormDefault values to determine whether an element or attribute is qualified. The XML code below shows a schema:

              <schema elementFormDefault="qualified" 
              attributeFormDefault="unqualified" ... >
               <element name="Name"/>
               <attribute name="Number"/>
              </schema>
            
When the XmlSerializer reads the schema, the XmlAttributeAttribute.Form value for both the Name and Number will be XmlSchemaForm.None, but the Name element will be qualified, while the Number element will be unqualified.
Example
The following example sets the XmlElementAttribute.Form property to XmlSchemaForm.Unqualified.
public class MyClass
{
   [XmlElement(Form = XmlSchemaForm.Unqualified)]
   public string ClassName;
}


    

Return to top


Property: IsNullable (read-write)
Summary
Gets or sets a value indicating whether the XmlSerializer should serialize a member that is set to null as an empty 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, "XML Schema Part 1: Structures".

If the XmlElementAttribute.IsNullable property is set to 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 XmlElementAttribute.IsNullable property is false, no XML element is generated.



Note You cannot apply the XmlElementAttribute.IsNullable property to a member typed as a value type because a value type cannot contain null.
Example
The following example shows a field attributed with the XmlElementAttribute, and the XmlElementAttribute.IsNullable property set to false.
public class MyClass
{
   [XmlElement(IsNullable = false)]
   public string Group;
}


    

Return to top


Property: Namespace (read-write)
Summary
Gets or sets the namespace assigned to the XML element that results when the class is serialized.
C# Syntax:
public string Namespace {get; set;}
Remarks
The XmlArrayItemAttribute.Namespace property conforms to the World Wide Web Consortium (www.w3.org) specification, "Namespaces in XML".

To create namespaces that are associated with a prefix, you must create an XmlSerializerNamespaces that contains the namespaces and prefixes used in the XML document. As you set the namespace for each XmlArrayAttribute, it must match one of the namespaces in the XmlSerializerNamespaces. When the XML is generated, each array will be correctly prefixed with the prefix associated with the specified namespace.

Return to top


Property: Type (read-write)
Summary
Gets or sets the object type used to represent the XML element.
C# Syntax:
public Type Type {get; set;}
Remarks
Use the XmlElementAttribute.Type property to specify a derived type for a field or property.

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

Example
The following example uses the XmlElementAttribute.Type property to specify a derived object for an XmlElementAttribute. The example also applies three instances of the XmlElementAttribute to a field that returns an ArrayList. Each instance specifies a type allowed in the field.
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Group
{
   [XmlElement(typeof(Manager))]
   public Employee [] Staff;

   [XmlElement (typeof(int)),
   XmlElement (typeof(string)),
   XmlElement (typeof(DateTime))]
   public ArrayList 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("TypeEx.xml");
   }

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

      // Create object and serialize it.
      Group myGroup = new Group();
      
      Manager e1 = new Manager();
      e1.Name = "Manager1";
      Manager m1 =  new Manager();
      m1.Name = "Manager2";
      m1.Level = 4;

      Employee[] emps = {e1, m1};
      myGroup.Staff = emps;

      myGroup.ExtraInfo = new ArrayList();
      myGroup.ExtraInfo.Add(".NET");
      myGroup.ExtraInfo.Add(42);
      myGroup.ExtraInfo.Add(new DateTime(2001,1,1));
      
      TextWriter writer = new StreamWriter(filename);
      xSer.Serialize(writer, myGroup);
      writer.Close();
   }
}


    

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:
~XmlElementAttribute();

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.