Export (0) Print
Expand All

XmlArrayAttribute Class

Specifies that the XmlSerializer should serialize a particular class member as an array of XML elements.

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

System.Object
   System.Attribute
      System.Xml.Serialization.XmlArrayAttribute

[Visual Basic]
<AttributeUsage(AttributeTargets.Property Or AttributeTargets.Field _
   Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue)>
Public Class XmlArrayAttribute
   Inherits Attribute
[C#]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field
   | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlArrayAttribute : Attribute
[C++]
[AttributeUsage(AttributeTargets::Property |
   AttributeTargets::Field | AttributeTargets::Parameter |
   AttributeTargets::ReturnValue)]
public __gc class XmlArrayAttribute : public Attribute
[JScript]
public
   AttributeUsage(AttributeTargets.Property | AttributeTargets.Field |
   AttributeTargets.Parameter | AttributeTargets.ReturnValue)
class XmlArrayAttribute 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 XmlArrayAttribute 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.

You can apply the XmlArrayAttribute to a public field or read/write property that returns an array of objects. You can also apply it to collections, and fields that return an ArrayList or any field that returns an object that implements the IEnumerable interface.

When you apply the XmlArrayAttribute to a class member, the XmlSerializer class's Serialize method generates a nested sequence of XML elements from that member. An XML schema document (an .xsd file), indicates such an array as a complexType. For example, if the class to be serialized represents a purchase order, you can generate an array of purchased items by applying the XmlArrayAttribute to a public field that returns an array of objects that represent order items.

If no attributes are applied to a public field or property that returns an array of complex or primitive type objects, the XmlSerializer generates a nested sequence of XML elements by default. To more precisely control what XML elements are generated, apply an XmlArrayItemAttribute and an XmlArrayAttribute to the field or property. For example, by default, the name of the generated XML element is derived from the member identifier; you can change the name of the generated XML element by setting the ElementName property.

If you serialize an array that contains items of a specific type and all the classes derived from that type, you must use the XmlArrayItemAttribute to declare each of the types.

Note   In your code, you can use XmlArray instead of the longer XmlArrayAttribute.

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

Example

[Visual Basic, C#, C++] The following example serializes a class instance into an XML document containing several object arrays. The XmlArrayAttribute is applied to the members that become XML-element arrays.

[Visual Basic] 
Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml.Serialization
Imports System.Xml


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeDocument("books.xml")
    End Sub
    
    
    Public Sub SerializeDocument(ByVal filename As String)
        ' Creates a new XmlSerializer.
        Dim s As New XmlSerializer(GetType(MyRootClass))
        
        ' Writing the file requires a StreamWriter.
        Dim myWriter As New StreamWriter(filename)
        
        ' Creates an instance of the class to serialize. 
        Dim myRootClass As New MyRootClass()
        
        ' Uses a basic method of creating an XML array: Create and
        ' populate a string array, and assign it to the
        ' MyStringArray property. 
        
        Dim myString() As String =  {"Hello", "world", "!"}
        myRootClass.MyStringArray = myString
        
        ' Uses a more advanced method of creating an array:
        ' create instances of the Item and BookItem, where BookItem
        ' is derived from Item. 
        Dim item1 As New Item()
        Dim item2 As New BookItem()
        
        ' Sets the objects' properties.
        With item1
            .ItemName = "Widget1"
            .ItemCode = "w1"
            .ItemPrice = 231
            .ItemQuantity = 3
        End With

        With item2
            .ItemCode = "w2"
            .ItemPrice = 123
            .ItemQuantity = 7
            .ISBN = "34982333"
            .Title = "Book of Widgets"
            .Author = "John Smith"
        End With
        
        ' Fills the array with the items.
        Dim myItems() As Item =  {item1, item2}
        
        ' Set class's Items property to the array.
        myRootClass.Items = myItems
        
        ' Serializes the class, writes it to disk, and closes
        ' the TextWriter. 
        s.Serialize(myWriter, myRootClass)
        myWriter.Close()
    End Sub
End Class


' This is the class that will be serialized.
Public Class MyRootClass
    Private myItems() As Item
    
    ' Here is a simple way to serialize the array as XML. Using the
    ' XmlArrayAttribute, assign an element name and namespace. The
    ' IsNullable property determines whether the element will be
    ' generated if the field is set to a null value. If set to true,
    ' the default, setting it to a null value will cause the XML
    ' xsi:null attribute to be generated.
    <XmlArray(ElementName := "MyStrings", _
         Namespace := "http://www.cpandl.com", _
         IsNullable := True)> _
    Public MyStringArray() As String
    
    ' Here is a more complex example of applying an
    ' XmlArrayAttribute. The Items property can contain both Item
    ' and BookItem objects. Use the XmlArrayItemAttribute to specify
    ' that both types can be inserted into the array.
    <XmlArrayItem(ElementName := "Item", _
        IsNullable := True, _
        Type := GetType(Item), _
        Namespace := "http://www.cpandl.com"), _
     XmlArrayItem(ElementName := "BookItem", _
        IsNullable := True, _
        Type := GetType(BookItem), _
        Namespace := "http://www.cohowinery.com"), _
     XmlArray()> _
    Public Property Items As Item()
        Get
            Return myItems
        End Get
        Set
            myItems = value
        End Set
    End Property
End Class
 
Public Class Item
    <XmlElement(ElementName := "OrderItem")> _
    Public ItemName As String
    Public ItemCode As String
    Public ItemPrice As Decimal
    Public ItemQuantity As Integer
End Class

Public Class BookItem
    Inherits Item
    Public Title As String
    Public Author As String
    Public ISBN As String
End Class


[C#] 
using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
 
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeDocument("books.xml");
   }
 
   public void SerializeDocument(string filename)
   {
      // Creates a new XmlSerializer.
      XmlSerializer s = 
      new XmlSerializer(typeof(MyRootClass));

      // Writing the file requires a StreamWriter.
      TextWriter myWriter= new StreamWriter(filename);

      // Creates an instance of the class to serialize. 
      MyRootClass myRootClass = new MyRootClass();

      /* Uses a basic method of creating an XML array: Create and 
      populate a string array, and assign it to the 
      MyStringArray property. */

      string [] myString = {"Hello", "world", "!"};
      myRootClass.MyStringArray = myString;
       
      /* Uses a more advanced method of creating an array:
         create instances of the Item and BookItem, where BookItem 
         is derived from Item. */
      Item item1 = new Item();
      BookItem item2 = new BookItem();
  
      // Sets the objects' properties.
      item1.ItemName = "Widget1";
      item1.ItemCode = "w1";
      item1.ItemPrice = 231;
      item1.ItemQuantity = 3;
 
      item2.ItemCode = "w2";
      item2.ItemPrice = 123;
      item2.ItemQuantity = 7;
      item2.ISBN = "34982333";
      item2.Title = "Book of Widgets";
      item2.Author = "John Smith";
       
      // Fills the array with the items.
      Item [] myItems = {item1,item2};
       
      // Sets the class's Items property to the array.
      myRootClass.Items = myItems;
 
      /* Serializes the class, writes it to disk, and closes 
         the TextWriter. */
      s.Serialize(myWriter, myRootClass);
      myWriter.Close();
   }
}

// This is the class that will be serialized.
public class MyRootClass
{
   private Item [] items;
 
   /* Here is a simple way to serialize the array as XML. Using the
      XmlArrayAttribute, assign an element name and namespace. The
      IsNullable property determines whether the element will be 
      generated if the field is set to a null value. If set to true,
      the default, setting it to a null value will cause the XML
      xsi:null attribute to be generated. */
   [XmlArray(ElementName = "MyStrings",
   Namespace = "http://www.cpandl.com", IsNullable = true)]
   public string[] MyStringArray;
  
   /* Here is a more complex example of applying an 
      XmlArrayAttribute. The Items property can contain both Item 
      and BookItem objects. Use the XmlArrayItemAttribute to specify
      that both types can be inserted into the array. */
   [XmlArrayItem(ElementName= "Item", 
   IsNullable=true,
   Type = typeof(Item),
   Namespace = "http://www.cpandl.com"),
   XmlArrayItem(ElementName = "BookItem", 
   IsNullable = true, 
   Type = typeof(BookItem),
   Namespace = "http://www.cohowinery.com")]
   [XmlArray]
   public Item []Items
   {
      get{return items;}
      set{items = value;}
   }
}
 
public class Item{
   [XmlElement(ElementName = "OrderItem")]
   public string ItemName;
   public string ItemCode;
   public decimal ItemPrice;
   public int ItemQuantity;
}
 
public class BookItem:Item
{
   public string Title;
   public string Author;
   public string ISBN;
}
   

[C++] 
#using <mscorlib.dll>
#using <System.Xml.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;
using namespace System::Xml;
 
public __gc class Item{
public:
   [XmlElement(ElementName = S"OrderItem")]
   String* ItemName;
   String* ItemCode;
   Decimal ItemPrice;
   int ItemQuantity;
};
 
public __gc class BookItem:public Item
{
public:
   String* Title;
   String* Author;
   String* ISBN;
};
   
// This is the class that will be serialized.
public __gc class MyRootClass
{
private:
   Item* items[];
 
   /* Here is a simple way to serialize the array as XML. Using the
      XmlArrayAttribute, assign an element name and namespace. The
      IsNullable property determines whether the element will be 
      generated if the field is set to a null value. If set to true,
      the default, setting it to a null value will cause the XML
      xsi:null attribute to be generated. */
public:
   [XmlArray(ElementName = S"MyStrings",
   Namespace = S"http://www.cpandl.com", IsNullable = true)]
   String* MyStringArray[];
  
   /* Here is a more complex example of applying an 
      XmlArrayAttribute. The Items property can contain both Item 
      and BookItem objects. Use the XmlArrayItemAttribute to specify
      that both types can be inserted into the array. */
   [XmlArrayItem(ElementName= S"Item", 
   IsNullable=true,
   Type = __typeof(Item),
   Namespace = S"http://www.cpandl.com"),
   XmlArrayItem(ElementName = S"BookItem", 
   IsNullable = true, 
   Type = __typeof(BookItem),
   Namespace = S"http://www.cohowinery.com")]
   [XmlArray]
   __property Item* get_Items()[]{return items;}
   __property void set_Items( Item* value[] ){items = value;}
   
};
 
public __gc class Run
{
public:
   void SerializeDocument(String* filename)
   {
      // Creates a new XmlSerializer.
      XmlSerializer* s = 
      new XmlSerializer(__typeof(MyRootClass));

      // Writing the file requires a StreamWriter.
      TextWriter* myWriter= new StreamWriter(filename);

      // Creates an instance of the class to serialize. 
      MyRootClass* myRootClass = new MyRootClass();

      /* Uses a basic method of creating an XML array: Create and 
      populate a string array, and assign it to the 
      MyStringArray property. */

      String* myString[] = {S"Hello", S"world", S"!"};
      myRootClass->MyStringArray = myString;
       
      /* Uses a more advanced method of creating an array:
         create instances of the Item and BookItem, where BookItem 
         is derived from Item. */
      Item* item1 = new Item();
      BookItem* item2 = new BookItem();
  
      // Sets the objects' properties.
      item1->ItemName = S"Widget1";
      item1->ItemCode = S"w1";
      item1->ItemPrice = 231;
      item1->ItemQuantity = 3;
 
      item2->ItemCode = S"w2";
      item2->ItemPrice = 123;
      item2->ItemQuantity = 7;
      item2->ISBN = S"34982333";
      item2->Title = S"Book of Widgets";
      item2->Author = S"John Smith";
       
      // Fills the array with the items.
      Item* myItems[] = {item1,item2};
       
      // Sets the class's Items property to the array.
      myRootClass->Items = myItems;
 
      /* Serializes the class, writes it to disk, and closes 
         the TextWriter. */
      s->Serialize(myWriter, myRootClass);
      myWriter->Close();
   }
};

int main()
{
   Run* test = new Run();
   test->SerializeDocument(S"books.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

XmlArrayAttribute Members | System.Xml.Serialization Namespace | XmlArray | XmlArrayItemAttribute | XmlAttributeOverrides | XmlAttributes | XmlSerializer | Introducing XML Serialization | Overriding XML Serialization | XmlAttributes | Controlling XML Serialization Using Attributes | Examples of XML Serialization

Show:
© 2014 Microsoft