[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] |
The XmlArrayAttribute can be applied to a public field or read/write property that returns an array of objects. It can also be applied to collections, and fields that return an ArrayList or any class that implements the IEnumerable interface.
When you apply the XmlArrayAttribute to a class member, the XmlSerializer class's XmlSerializer.Serialize method generates a nested sequence of XML elements from that member. (An XML schema document (or .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 XmlArrayAttribute.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.
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) { // Create a new XmlSerializer. XmlSerializer s = new XmlSerializer(typeof(MyRootClass)); // Writing the file requires a StreamWriter. TextWriter myWriter= new StreamWriter(filename); // Create an instance of the class to serialize. MyRootClass myRootClass = new MyRootClass(); /* Use 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; /* Use more advanced method of creating an array. Create instances of the Item and BookItem. BookItem is derived from Item. */ Item item1 = new Item(); BookItem item2 = new BookItem(); // Set 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"; // Fill array with the items. Item [] myItems = {item1,item2}; // Set class's Items property to the array. myRootClass.Items = myItems; /* Serialize the class, write it to disk, and close 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; }
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 XmlArrayAttribute class. |
ctor #2 | Overloaded:.ctor(string elementName) Initializes a new instance of the XmlArrayAttribute class; specifies the XML element name generated in the XML-document instance. |
ElementName | Read-write Gets or sets the XML element name given to the serialized array. |
Form | Read-write Gets or sets a value indicating whether the XML element name generated by the XmlSerializer is qualified or unqualified. |
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 set the namespace of 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. |
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. |
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:
public XmlArrayAttribute(); |
public class MyClass { [XmlArrayAttribute()] public string [] MyStringArray; [XmlArrayAttribute()] public int [] MyIntegerArray; }
public XmlArrayAttribute( |
elementName
using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class MyClass{ [XmlArrayAttribute("MyStrings")] public string [] MyStringArray; [XmlArrayAttribute(ElementName = "MyIntegers")] public int [] MyIntegerArray; } public class Run{ public static void Main() { Run test = new Run(); test.SerializeObject("MyClass.xml"); } public void SerializeObject(string filename) { // Create a new instance of the XmlSerializer class. XmlSerializer s = new XmlSerializer(typeof(MyClass)); // A StreamWriter is needed to write the file. TextWriter myWriter= new StreamWriter(filename); MyClass myClass = new MyClass(); // Create and populate a string array, the assign // it to the MyStringArray property. string [] myStrings = {"Hello", "World", "!"}; myClass.MyStringArray = myStrings; /* Create and populate an integer array, and assign it to the MyIntegerArray property. */ int [] myIntegers = {1,2,3}; myClass.MyIntegerArray = myIntegers; // Serialize the class, and write it to disk. s.Serialize(myWriter, myClass); myWriter.Close(); } }
public string ElementName {get; set;}
|
You can set the same XmlArrayAttribute.ElementName value to more than one member as long as the generated XML document uses XML namespaces to distinguish between the identically named members. For more details on using namespaces and creating prefixed names in the XML document, see XmlSerializerNamespaces.
using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Library { private Book[] books; [XmlArray(ElementName="My_Books")] public Book[] Books { get{return books;} set{books = value;} } } public class Book { public string Title; public string Author; public string ISBN; } public class Run { public static void Main() { Run test = new Run(); test.WriteBook("ArrayExample.xml"); } public void WriteBook(string filename) { XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); TextWriter t = new StreamWriter(filename); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("bk", "http://wwww.contoso.com"); Book b1 = new Book(); b1.Title = "MyBook Title"; b1.Author = "An Author"; b1.ISBN = "00000000"; Book b2 = new Book(); b2.Title = "Another Title"; b2.Author = "Another Author"; b2.ISBN = "0000000"; Library myLibrary = new Library(); Book[] myBooks = {b1,b2}; myLibrary.Books = myBooks; mySerializer.Serialize(t,myLibrary,ns); t.Close(); } }
public XmlSchemaForm Form {get; set;}
|
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.
using System; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; public class Enterprises { private Winery[] wineries; private VacationCompany[] companies; // Set the Form property to qualified, and specify the Namespace. [XmlArray(Form = XmlSchemaForm.Qualified, ElementName="Company", Namespace="http://www.cohowinery.com")] public Winery[] Wineries{ get{return wineries;} set{wineries = value;} } [XmlArray(Form = XmlSchemaForm.Qualified, ElementName = "Company", Namespace = "http://www.treyresearch.com")] public VacationCompany [] Companies{ get{return companies;} set{companies = value;} } } public class Winery { public string Name; } public class VacationCompany{ public string Name; } public class Run { public static void Main() { Run test = new Run(); test.WriteEnterprises("MyEnterprises.xml"); } public void WriteEnterprises(string filename) { // Create an instance of the XmlSerializer class. XmlSerializer mySerializer = new XmlSerializer(typeof(Enterprises)); // Writing file requires a TextWriter. TextWriter writer = new StreamWriter(filename); // Create an instance of the XmlSerializerNamespaces class. XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); // Add namespaces and prefixes for the XML-instance document. ns.Add("winery", "http://www.cohowinery.com"); ns.Add("vacationCompany", "http://www.treyresearch.com"); // Create an instance of the class that will be serialized. Enterprises myEnterprises = new Enterprises(); // Create objects and add to the array. Winery w1= new Winery(); w1.Name = "cohowinery"; Winery[]myWinery = {w1}; myEnterprises.Wineries = myWinery; VacationCompany com1 = new VacationCompany(); com1.Name = "adventure-works"; VacationCompany[] myCompany = {com1}; myEnterprises.Companies = myCompany; // Serialize the class, and close the TextWriter. mySerializer.Serialize(writer, myEnterprises, ns); writer.Close(); } public void ReadEnterprises(string filename) { XmlSerializer mySerializer = new XmlSerializer(typeof(Enterprises)); FileStream fs = new FileStream(filename, FileMode.Open); Enterprises myEnterprises = (Enterprises) mySerializer.Deserialize(fs); for(int i = 0; i < myEnterprises.Wineries.Length;i++) { Console.WriteLine(myEnterprises.Wineries[i].Name); } for(int i = 0; i < myEnterprises.Companies.Length;i++) { Console.WriteLine(myEnterprises.Companies[i].Name); } } }
public bool IsNullable {get; set;}
|
If the XmlArrayAttribute.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 XmlArrayAttribute.IsNullable property is false, no XML element is generated.
public class MyClass { [XmlArray (IsNullable = true)] public string [] IsNullableIsTrueArray; [XmlArray (IsNullable = false)] public string [] IsNullableIsFalseArray; }
public string Namespace {get; set;}
|
To create namespaces that are associated with a prefix, you must create an XmlSerializerNamespaces object 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 object. When the XML is generated, each array will be correctly prefixed with the prefix associated with the specified namespace.
using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Library { private Book[] books; private Periodical [] periodicals; /* This element will be qualified with the prefix that is associated with the namespace http://wwww.cpandl.com. */ [XmlArray(ElementName = "Titles", Namespace="http://wwww.cpandl.com")] public Book[] Books { get{return books;} set{books = value;} } /* This element will be qualified with the prefix that is associated with the namespace http://www.proseware.com. */ [XmlArray(ElementName = "Titles", Namespace = "http://www.proseware.com")] public Periodical[] Periodicals { get{return periodicals;} set{periodicals = value;} } } public class Book { public string Title; public string Author; public string ISBN; [XmlAttribute] public string Publisher; } public class Periodical { private string title; public string Title { get{return title;} set{title = value;} } } public class Run { public static void Main() { Run test = new Run(); test.WriteBook("MyLibrary.xml"); test.ReadBook("MyLibrary.xml"); } public void WriteBook(string filename) { // Create a new XmlSerializer instance. XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); // Writing the file requires a StreamWriter. TextWriter myStreamWriter = new StreamWriter(filename); /* Create an XmlSerializerNamespaces and add prefixes and namespaces to be used. */ XmlSerializerNamespaces myNamespaces = new XmlSerializerNamespaces(); myNamespaces.Add("books", "http://wwww.cpandl.com"); myNamespaces.Add("magazines", "http://www.proseware.com"); // Create an instance of the class to be serialized. Library myLibrary = new Library(); // Create two book objects. Book b1 = new Book(); b1.Title = "My Book Title"; b1.Author = "An Author"; b1.ISBN = "000000000"; b1.Publisher = "Microsoft Press"; Book b2 = new Book(); b2.Title = "Another Book Title"; b2.Author = "Another Author"; b2.ISBN = "00000001"; b2.Publisher = "Another Press"; /* Create an array using the objects, and set the Books property to the array. */ Book[] myBooks = {b1,b2}; myLibrary.Books = myBooks; // Create two Periodical objects. Periodical per1 = new Periodical(); per1.Title = "My Magazine Title"; Periodical per2 = new Periodical(); per2.Title = "Another Magazine Title"; // Set the Periodicals property to the array. Periodical[] myPeridocials = {per1, per2}; myLibrary.Periodicals = myPeridocials; // Serialize the myLibrary object. mySerializer.Serialize(myStreamWriter, myLibrary, myNamespaces); myStreamWriter.Close(); } public void ReadBook(string filename) { /* Read the XML document. First create an instance of an XmlSerializer using the class used to read the document. */ XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); // A FileStream is needed to read the file. FileStream myFileStream = new FileStream(filename, FileMode.Open); Library myLibrary = (Library) mySerializer.Deserialize(myFileStream); // Read each book in the array returned by the Books property. for(int i = 0; i< myLibrary.Books.Length;i++) { Console.WriteLine(myLibrary.Books[i].Title); Console.WriteLine(myLibrary.Books[i].Author); Console.WriteLine(myLibrary.Books[i].ISBN); Console.WriteLine(myLibrary.Books[i].Publisher); Console.WriteLine(); } // Read each Periodical returned by the Periodicals property. for(int i = 0; i< myLibrary.Periodicals.Length;i++) { Console.WriteLine(myLibrary.Periodicals[i].Title); } } }
public virtual object TypeId {get;}
|
~XmlArrayAttribute(); |
public override int GetHashCode(); |
public Type GetType(); |
public virtual bool IsDefaultAttribute(); |
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.
obj
protected object MemberwiseClone(); |
public virtual string ToString(); |