Export (0) Print
Expand All

XmlElementAttribute Class

Indicates that a public field or property represents an XML element when the XmlSerializer serializes or deserializes the containing object.

For a list of all members of this type, see XmlElementAttribute Members.

System.Object
   System.Attribute
      System.Xml.Serialization.XmlElementAttribute

[Visual Basic]
<AttributeUsage(AttributeTargets.Property Or AttributeTargets.Field _
   Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue)>
Public Class XmlElementAttribute
   Inherits Attribute
[C#]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field
   | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlElementAttribute : Attribute
[C++]
[AttributeUsage(AttributeTargets::Property |
   AttributeTargets::Field | AttributeTargets::Parameter |
   AttributeTargets::ReturnValue)]
public __gc class XmlElementAttribute : public Attribute
[JScript]
public
   AttributeUsage(AttributeTargets.Property | AttributeTargets.Field |
   AttributeTargets.Parameter | AttributeTargets.ReturnValue)
class XmlElementAttribute extends Attribute

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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 Attributes That Control XML Serialization.

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 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 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 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 Type property to a type of object that can be inserted into the array.

For more information about using attributes, see Extending Metadata Using Attributes.

Note   In your code, you can use the word XmlElement instead of the longer XmlElementAttribute.

Example

[Visual Basic, C#, C++] 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).

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.IO
Imports System.Xml.Serialization


Public Class Group
    ' Set the element name and namespace of the XML element.
    <XmlElement(ElementName := "Members", _
     Namespace := "http://www.cpandl.com")> _    
    Public Employees() As Employee
    
    <XmlElement(DataType := "double", _
     ElementName := "Building")> _
    Public GroupID As Double
    
    <XmlElement(DataType := "hexBinary")> _
    Public HexBytes() As Byte
    
    <XmlElement(DataType := "boolean")> _
    Public IsActive As Boolean
    
    <XmlElement(GetType(Manager))> _
    Public Manager As Employee
    
    <XmlElement(GetType(Integer), _
        ElementName := "ObjectNumber"), _
     XmlElement(GetType(String), _
        ElementName := "ObjectString")> _
    Public ExtraInfo As ArrayList
End Class

Public Class Employee
    Public Name As String
End Class

Public Class Manager
    Inherits Employee
    Public Level As Integer
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("FirstDoc.xml")
        test.DeserializeObject("FirstDoc.xml")
    End Sub
    
    Public Sub SerializeObject(filename As String)
        ' Create the XmlSerializer.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        ' Create an instance of the group to serialize, and set
        ' its properties. 
        Dim group As New Group()
        group.GroupID = 10.089f
        group.IsActive = False
        
        group.HexBytes = New Byte() {Convert.ToByte(100)}
        
        Dim x As New Employee()
        Dim y As New Employee()
        
        x.Name = "Jack"
        y.Name = "Jill"
        
        group.Employees = New Employee() {x, y}
        
        Dim mgr As 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()
    End Sub    
    
    Public Sub DeserializeObject(filename As String)
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim x As New XmlSerializer(GetType(Group))
        Dim g As Group = CType(x.Deserialize(fs), Group)
        Console.WriteLine(g.Manager.Name)
        Console.WriteLine(g.GroupID)
        Console.WriteLine(g.HexBytes(0))

        Dim e As Employee
        For Each e In g.Employees
            Console.WriteLine(e.Name)
        Next e
    End Sub
End Class


[C#] 
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);
      }
   }
}
   

[C++] 
#using <mscorlib.dll>
#using <System.Xml.dll>
#using <System.dll>
using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Xml::Serialization;

public __gc class Employee
{
public:
   String* Name;
};

public __gc class Manager: public Employee{
public:
   int Level;
};

public __gc class Group
{
public:
   /* 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 = S"Members",
      Namespace = S"http://www.cpandl.com")]
   Employee* Employees[];

   [XmlElement(DataType = S"double",
      ElementName = S"Building")]
   double GroupID;

   [XmlElement(DataType = S"hexBinary")]
   Byte HexBytes[];

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

   [XmlElement(Type = __typeof(::Manager))]
   Employee* Manager;

   [XmlElement(__typeof(Int32),
      ElementName = S"ObjectNumber"),
      XmlElement(__typeof(String),
      ElementName = S"ObjectString")]
   ArrayList* ExtraInfo;
};

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;

   Byte temp0 [] = {Convert::ToByte(100)};
   group->HexBytes = temp0;

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

   x->Name = S"Jack";
   y->Name = S"Jill";

   Employee* temp1 [] = {x,y};
   group->Employees = temp1;

   Manager* mgr = new Manager();
   mgr->Name = S"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(__box(42));
   group->ExtraInfo->Add(S"Answer");

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

void DeserializeObject(String* filename)
{
   FileStream* fs = new FileStream(filename, FileMode::Open);
   XmlSerializer* x = new XmlSerializer(__typeof(Group));
   Group* g = dynamic_cast<Group*> (x->Deserialize(fs));
   Console::WriteLine(g->Manager->Name);
   Console::WriteLine(g->GroupID);
   Console::WriteLine(g->HexBytes[0]);
   IEnumerator* myEnum = g->Employees->GetEnumerator();
   while (myEnum->MoveNext())
   {
      Employee* e = __try_cast<Employee*>(myEnum->Current);
      Console::WriteLine(e->Name);
   }
}

int main()
{
   SerializeObject(S"FirstDoc.xml");
   DeserializeObject(S"FirstDoc.xml");
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Xml.Serialization

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: System.Xml (in System.Xml.dll)

See Also

XmlElementAttribute Members | System.Xml.Serialization Namespace | XmlArrayAttribute | XmlAttributeOverrides | XmlAttributes | XmlElementAttributes | XmlElements | XmlRootAttribute | XmlSerializer | Introducing XML Serialization | Overriding XML Serialization | XmlAttributes | Controlling XML Serialization Using Attributes | Examples of XML Serialization

Show:
© 2014 Microsoft