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 object that contains it.

Namespace: System.Xml.Serialization
Assembly: System.Xml (in system.xml.dll)

'Declaration
<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple:=True)> _
Public Class XmlElementAttribute
	Inherits Attribute
'Usage
Dim instance As XmlElementAttribute

/** @attribute AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=true) */ 
public class XmlElementAttribute extends Attribute
AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=true) 
public class XmlElementAttribute extends Attribute

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 following C# code 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.

NoteNote

You can use the word XmlElement in your code instead of the longer XmlElementAttribute.

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 the resulting XML will not be nested (which is the default behavior of items in an array).

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


import System.*;
import System.Collections.*;
import System.IO.*;
import 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. */
   
    /** @attribute XmlElement(ElementName = "Members",
        Namespace = "http://www.cpandl.com")
     */
    public Employee employees[];   
    /** @attribute XmlElement(DataType = "double", ElementName = "Building")
     */
    public double groupID;   
    /** @attribute XmlElement(DataType = "hexBinary")
     */
    public ubyte hexBytes[];   
    /** @attribute XmlElement(DataType = "boolean")
     */
    public boolean isActive;   
    /** @attribute XmlElement(Type = Manager.class)
     */
    public Employee manager;   
    /** @attribute XmlElement(int.class, ElementName = "ObjectNumber")
        @attribute XmlElement(String.class, ElementName = "ObjectString")
     */
    public ArrayList extraInfo;
} //Group

public class Employee
{
    public String name;
} //Employee

public class Manager extends Employee
{
    public int level;
} //Manager

public class Run
{
    public static void main(String[] args)
    {
        Run test = new Run();
        test.SerializeObject("FirstDoc.xml");
        test.DeserializeObject("FirstDoc.xml");
    } //main

    public void SerializeObject(String fileName)
    {
        // Create the XmlSerializer.
        XmlSerializer s = new XmlSerializer(Group.class.ToType());

        // 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 ubyte[] { Convert.ToByte(100) };

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

        x.name = "Jack";
        y.name = "Jill";
        group.employees = new Employee[] { 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((Int32)42);
        group.extraInfo.Add("Answer");

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

    public void DeserializeObject(String fileName)
    {
        FileStream fs = new FileStream(fileName, FileMode.Open);
        XmlSerializer x = new XmlSerializer(Group.class.ToType());
        Group g = (Group)x.Deserialize(fs);

        Console.WriteLine(g.manager.name);
        Console.WriteLine(g.groupID);
        Console.WriteLine(g.hexBytes.get_Item(0));
        for (int iCtr = 0; iCtr < g.employees.length; iCtr++) {
            Employee e = g.employees[iCtr];
            Console.WriteLine(e.name);
        }
    } //DeserializeObject
} //Run

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

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

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft