[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] |
You can apply the XmlArrayItemAttribute to any public read/write member that returns an array, or provides access to one (for example, a field that returns an array of objects, a collection, an ArrayList, or any class that implements the IEnumerable interface).
The XmlArrayItemAttribute supports polymorphism--in other words, it allows the XmlSerializer to add derived objects to an array. For example, suppose a class named
Mammal
is derived from a base class named
Animal
. Further suppose that a class named
MyAnimals
contains a field that returns an array of
Animal
objects. To allow the XmlSerializer to serialize both the
Animal
and
Mammal
type, apply the XmlArrayItemAttribute to the field twice, each time specifying one of the two acceptable types.
For more information about using attributes, see the conceptual topic at MSDN: extendingmetadatausingattributes.
Group
, which contains a field named
Employees
that returns an array of
Employee
objects. The example applies the XmlArrayItemAttribute to the field, thereby instructing the XmlSerializer that it can insert objects of both the base class (
Employee
) type and derived class type (
Manager
) into the serialized array.using System; using System.IO; using System.Xml.Serialization; public class Group { /* The XmlArrayItemAttribute allows the XmlSerializer to insert both the base type (Employee) and derived type (Manager) into serialized arrays. */ [XmlArrayItem(typeof(Manager)), XmlArrayItem(typeof(Employee))] public Employee[] Employees; /* Use the XmlArrayItemAttribute to specify types allowed in an array of Object items. */ [XmlArray] [XmlArrayItem (typeof(int), ElementName = "MyNumber"), XmlArrayItem (typeof(string), ElementName = "MyString"), XmlArrayItem(typeof(Manager))] public object [] 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("TypeDoc.xml"); test.DeserializeObject("TypeDoc.xml"); } public void SerializeObject(string filename) { // Create a new XmlSerializer instance. XmlSerializer s = new XmlSerializer(typeof(Group)); // Writing the XML file to disk requires a TextWriter. TextWriter writer = new StreamWriter(filename); Group group = new Group(); Manager manager = new Manager(); Employee emp1 = new Employee(); Employee emp2 = new Employee(); manager.Name = "Consuela"; manager.Level = 3; emp1.Name = "Seiko"; emp2.Name = "Martina"; Employee [] emps = new Employee[3]{manager, emp1, emp2}; group.Employees = emps; // Create an int and a string and assign to ExtraInfo. group.ExtraInfo = new Object[3]{43, "Extra", manager}; // Serialize the object, and close the StreamWriter. 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("Members:"); foreach(Employee e in g.Employees) { Console.WriteLine("\t" + e.Name); } } }
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 XmlArrayItemAttribute class. |
ctor #2 | Overloaded:.ctor(string elementName) Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document. |
ctor #3 | Overloaded:.ctor(Type type) Initializes a new instance of the XmlArrayItemAttribute class; specifies the Type that can be inserted into the serialized array. |
ctor #4 | Overloaded:.ctor(string elementName, Type type) Initializes a new instance of the XmlArrayItemAttribute class; specifies the name of the XML element generated in the XML document, and the Type that can be inserted into the generated XML document. |
DataType | Read-write Gets or sets the XML data type of the generated XML element. |
ElementName | Read-write Gets or sets the name of the generated XML element. |
Form | Read-write Gets or sets a value indicating whether the name of the generated XML element is qualified. |
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 sets the namespace of the generated XML element. |
NestingLevel | Read-write Gets or sets the level in a hierarchy of XML elements that the XmlArrayItemAttribute affects. |
Type | Read-write Gets or sets the type allowed in an array. |
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 XmlArrayItemAttribute(); |
Transportation
which contains a field named
MyVehicles
that returns an array of
Vehicle
objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the
Car
class, which is derived from the
Vehicle
class, into the array.using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Vehicle { public string id; } public class Car:Vehicle { public string Maker; } public class Transportation { [XmlArrayItem(), XmlArrayItem(typeof(Car), ElementName = "Automobile")] public Vehicle[] MyVehicles; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("XmlArrayItem1.xml"); test.DeserializeObject("XmlArrayItem1.xml"); } private void SerializeObject(string filename){ // Create an XmlSerializer for the Transportation class. XmlSerializer MySerializer = new XmlSerializer(typeof(Transportation)); // Writing the XML file to disk requires a TextWriter. TextWriter myTextWriter = new StreamWriter(filename); // Create the object to serialize. Transportation myTransportation = new Transportation(); // Create objects to add to the array. Vehicle myVehicle= new Vehicle() ; myVehicle.id = "A12345"; Car myCar = new Car(); myCar.id = "Car 34"; myCar.Maker = "FamousCarMaker"; myTransportation.MyVehicles = new Vehicle[2] {myVehicle, myCar}; // Serialize the object, and close the StreamWriter. MySerializer.Serialize(myTextWriter, myTransportation); myTextWriter.Close(); } private void DeserializeObject(string filename) { // Create an XmlSerializer instance. XmlSerializer mySerializer = new XmlSerializer(typeof(Transportation)); FileStream myFileStream = new FileStream(filename,FileMode.Open); Transportation myTransportation = (Transportation) mySerializer.Deserialize(myFileStream); for(int i = 0; i < myTransportation.MyVehicles.Length;i++) { Console.WriteLine(myTransportation.MyVehicles[i].id); } } }
public XmlArrayItemAttribute( |
elementName
Use this overload if you want the name of the generated XML element to differ from the member's identifier.
An XML document that includes namespaces can contain more than one version of an element name. For details, see the XmlArrayItemAttribute.ElementName property.
Transportation
which contains a field named
MyVehicles
that returns an array of
Vehicle
objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the
Car
class, which is derived from the
Vehicle
class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.ElementName property using the elementName parameter.using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Vehicle { public string id; } public class Car:Vehicle { public string Maker; } public class Transportation { [XmlArrayItem(ElementName = "Transportation"), XmlArrayItem(typeof(Car), ElementName = "Automobile")] public Vehicle[] MyVehicles; } public class Run { public static void Main() { Run test= new Run(); test.SerializeObject("XmlArrayItem2.xml"); test.DeserializeObject("XmlArrayItem2.xml"); } private void SerializeObject(string filename) { // Create an XmlSerializer object for the Transportation class. XmlSerializer MySerializer = new XmlSerializer(typeof(Transportation)); // Writing the XML file to disk requires a TextWriter. TextWriter myTextWriter = new StreamWriter(filename); Transportation myTransportation = new Transportation(); Vehicle myVehicle= new Vehicle() ; myVehicle.id = "A12345"; Car myCar = new Car(); myCar.id = "Car 34"; myCar.Maker = "FamousCarMaker"; Vehicle [] myVehicles = {myVehicle, myCar}; myTransportation.MyVehicles = myVehicles; // Serialize the object, and close the StreamWriter. MySerializer.Serialize(myTextWriter, myTransportation); myTextWriter.Close(); } private void DeserializeObject(string filename) { // Create the serializer with the type to deserialize. XmlSerializer mySerializer = new XmlSerializer(typeof(Transportation)); FileStream myFileStream = new FileStream(filename,FileMode.Open); Transportation myTransportation = (Transportation) mySerializer.Deserialize(myFileStream); for(int i = 0;i < myTransportation.MyVehicles.Length;i++) { Console.WriteLine(myTransportation.MyVehicles[i].id); } } }
public XmlArrayItemAttribute( |
type
Transportation
which contains a field named
MyVehicles
that returns an array of
Vehicle
objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the
Car
class, which is derived from the
Vehicle
class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.Type property using the type parameter.using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Vehicle { public string id; } public class Car:Vehicle { public string Maker; } public class Transportation { [XmlArrayItem(typeof(Vehicle)), XmlArrayItem(typeof(Car))] public Vehicle[] MyVehicles; } public class Run { public static void Main() { Run test= new Run(); test.SerializeObject("XmlArrayItem3.xml"); test.DeserializeObject("XmlArrayItem3.xml"); } private void SerializeObject(string filename) { // Create an XmlSerializer object. XmlSerializer MySerializer = new XmlSerializer(typeof(Transportation)); // Writing the XML file to disk requires a TextWriter. TextWriter myTextWriter = new StreamWriter(filename); Transportation myTransportation = new Transportation(); Vehicle myVehicle= new Vehicle() ; myVehicle.id = "A12345"; Car myCar = new Car(); myCar.id = "Car 34"; myCar.Maker = "FamousCarMaker"; Vehicle [] myVehicles = {myVehicle, myCar}; myTransportation.MyVehicles = myVehicles; // Serialize the object, and close the StreamWriter. MySerializer.Serialize(myTextWriter, myTransportation); myTextWriter.Close(); } private void DeserializeObject(string filename) { // Create the serializer with the type to deserialize. XmlSerializer mySerializer = new XmlSerializer(typeof(Transportation)); FileStream myFileStream = new FileStream(filename,FileMode.Open); Transportation myTransportation = (Transportation) mySerializer.Deserialize(myFileStream); for(int i = 0;i < myTransportation.MyVehicles.Length;i++) { Console.WriteLine(myTransportation.MyVehicles[i].id); } } }
elementName
type
Use this overload if you want the name of the generated XML element to differ from the member's identifier.
An XML document that includes namespaces can contain more than one version of an element name. For details, see the XmlArrayItemAttribute.ElementName property.
Transportation
which contains a field named
MyVehicles
that returns an array of
Vehicle
objects. The example applies the XmlArrayItemAttribute to the field, allowing the XmlSerializer to insert instances of the
Car
class, which is derived from the
Vehicle
class, into the array. While applying the attribute, the example sets the XmlArrayItemAttribute.ElementName property using the elementName parameter, and the XmlArrayItemAttribute.Type property using the type parameter.using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Vehicle { public string id; } public class Car:Vehicle { public string Maker; } public class Transportation { [XmlArray] [XmlArrayItem("Transport", typeof(Vehicle)), XmlArrayItem("Automobile", typeof(Car))] public Vehicle[] MyVehicles; } public class Run { public static void Main() { Run test= new Run(); test.SerializeObject("XmlArrayItem4.xml"); test.DeserializeObject("XmlArrayItem4.xml"); } private void SerializeObject(string filename) { // Create an XmlSerializer object for the Transportation class. XmlSerializer MySerializer = new XmlSerializer(typeof(Transportation)); // Writing the XML file to disk requires a TextWriter. TextWriter myTextWriter = new StreamWriter(filename); Transportation myTransportation = new Transportation(); Vehicle myVehicle= new Vehicle() ; myVehicle.id = "A12345"; Car myCar = new Car(); myCar.id = "Car 34"; myCar.Maker = "FamousCarMaker"; Vehicle [] myVehicles = {myVehicle, myCar}; myTransportation.MyVehicles = myVehicles; // Serialize the object, and close the StreamWriter. MySerializer.Serialize(myTextWriter, myTransportation); myTextWriter.Close(); } private void DeserializeObject(string filename) { // Create an XmlSerializer object. XmlSerializer mySerializer = new XmlSerializer(typeof(Transportation)); FileStream myFileStream = new FileStream(filename,FileMode.Open); Transportation myTransportation = (Transportation) mySerializer.Deserialize(myFileStream); for(int i = 0;i < myTransportation.MyVehicles.Length;i++) { Console.WriteLine(myTransportation.MyVehicles[i].id); } } }
public string DataType {get; set;}
|
For the XML Schema base64Binary and hexBinary data types, use an array of Byte structures, and apply a XmlArrayItemAttribute with the XmlArrayItemAttribute.DataType property set to "base64Binary" or "hexBinary", as appropriate. For the XML Schema time and date data types, use the DateTime type and apply the XmlArrayItemAttribute with the XmlArrayItemAttribute.DataType set to "date" or "time".
For every XML Schema type that is mapped to a string, apply the XmlArrayItemAttribute with its XmlArrayItemAttribute.DataType property set to the XML Schema type. However, this will not change the serialization format, only the schema for the member.
For more information about XML Schema data types, see the World Wide Web Consortium (www.w3.org ) document "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 |
PurchaseOrder
. Several instances of the XmlArrayItemAttribute class are applied to three members, and the XmlArrayItemAttribute.DataType property for each instance is set to a type allowed in the array.using System; using System.Collections; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Xml.Schema; public class PurchaseOrder { [XmlArrayItem(DataType = "gMonth", ElementName="MyMonths", Namespace = "http://www.cohowinery.com")] public string[] Months; [XmlArrayItem(typeof(Item)), XmlArrayItem(typeof(NewItem))] public Item[] Items; [XmlArray(IsNullable = true)] [XmlArrayItem(typeof(string)), XmlArrayItem(typeof(double)), XmlArrayItem(typeof(NewItem))] public object[] Things; } public class Item{ public string ItemID; public Item(){} public Item(string id){ ItemID = id; } } public class NewItem:Item{ public string Category; public NewItem(){} public NewItem(string id, string cat){ this.ItemID = id; Category = cat; } } public class Test { public static void Main() { // Read and write purchase orders. Test t = new Test(); t.SerializeObject("ArrayItemEx.xml"); t.DeserializeObject("ArrayItemEx.xml"); } private void SerializeObject(string filename) { // Create an instance of the XmlSerializer class; // specify the type of object to serialize. XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder)); TextWriter writer = new StreamWriter(filename); // Create a PurchaseOrder and set its properties. PurchaseOrder po=new PurchaseOrder(); po.Months = new string[]{ "March", "May", "August"}; po.Items= new Item[]{new Item("a1"), new NewItem("b1", "book")}; po.Things= new object[] {"String", 2003.31, new NewItem("xxx", "book")}; // Serialize the purchase order, and close the TextWriter. serializer.Serialize(writer, po); writer.Close(); } protected void DeserializeObject(string filename) { // Create an instance of the XmlSerializer class; // specify the type of object to be deserialized. XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder)); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); // Declare an object variable of the type to be deserialized. PurchaseOrder po; /* Use the Deserialize method to restore the object's state with data from the XML document. */ po = (PurchaseOrder) serializer.Deserialize(fs); foreach(string s in po.Months) Console.WriteLine(s); foreach(Item i in po.Items) Console.WriteLine(i.ItemID); foreach(object thing in po.Things) Console.WriteLine(thing); } }
public string ElementName {get; set;}
|
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 identically named members. For details on how to use namespaces and prefixed names in the XML document, see the XmlSerializerNamespaces class.
Vehicle
and
Car
class--thereby changing the names of XML elements that the XmlSerializer generates for those classes.public class Transportation { [XmlArray("Vehicles")] /* Specify acceptable types and the ElementName generated for each object type. */ [XmlArrayItem(typeof(Vehicle), ElementName = "Transport"), XmlArrayItem(typeof(Car), ElementName = "Automobile")] public Vehicle[] MyVehicles; } // By default, this class results in XML elements named "Vehicle". public class Vehicle { public string id; } // By default, this class results in XML elements named "Car". public class Car:Vehicle { public string Maker; }
public XmlSchemaForm Form {get; set;}
|
Exception Type | Condition |
---|---|
Exception | The XmlArrayItemAttribute.Form property is set to XmlSchemaForm.Unqualified and a XmlArrayItemAttribute.Namespace value is specified. |
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 value, XmlSchemaForm.None, instructs the XmlSerializer to check the schema for the XML document to determine whether the namespace is qualified. For elements, the XmlSerializer checks the value of the schema-element attribute elementFormDefault. For attributes, it checks the value of the schema-element attribute attributeFormDefault . For example, the following XML Schema indicates that the Name element is qualified, while the Number element is unqualified.
<schema elementFormDefault="qualified" attributeFormDefault="unqualified"> <element name="Name"/> <attribute name="Number"/> </schema>
public class Transportation { [XmlArray("Vehicles")] // Specify the Form property value. [XmlArrayItem(typeof(Vehicle), Form = XmlSchemaForm.Unqualified), XmlArrayItem(typeof(Car), Form = XmlSchemaForm.Qualified)] public Vehicle[] MyVehicles; } public class Vehicle { public string id; } public class Car:Vehicle { public string Maker; }
public bool IsNullable {get; set;}
|
If the XmlArrayItemAttribute.IsNullable property is 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 XmlArrayItemAttribute.IsNullable property is false, no XML element is generated.
Group
, which contains a field named
Employees
that returns an array of
Employee
objects. A second class named
Manager
derives from
Employee
. An XmlArrayItemAttribute specifies that the XmlSerializer can insert both
Employee
and
Manager
objects into the array. The example sets the XmlArrayItemAttribute.IsNullable property, thereby telling the XmlSerializer not to generate the xsi:nil attribute objects in the array set to null.using System; using System.IO; using System.Xml.Serialization; public class Group { [XmlArray(IsNullable = true)] [XmlArrayItem(typeof(Manager), IsNullable = false), XmlArrayItem(typeof(Employee), IsNullable = false)] public Employee[] Employees; } 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("TypeDoc.xml"); } public void SerializeObject(string filename) { XmlSerializer s = new XmlSerializer(typeof(Group)); // To write the file, a TextWriter is required. TextWriter writer = new StreamWriter(filename); // Create the object to serialize. Group group = new Group(); // Create a null Manager object. Manager mgr = null; // Create a null Employee object. Employee y = null; group.Employees = new Employee[2] {mgr, y}; // Serialize the object and close the TextWriter. s.Serialize(writer, group); writer.Close(); } }
public string Namespace {get; set;}
|
To create namespaces to use in the XML document and associated prefixes, you must create an XmlSerializerNamespaces that contains all the prefix-namespace pairs. The namespace you set for each XmlArrayAttribute must be contained in the XmlSerializerNamespaces. When the XmlSerializer generates the document, it correctly prefixes the element name for each array item.
public class Transportation { // Set the Namespace property. [XmlArrayItem(typeof(Car), Namespace = "http://www.cpandl.com")] public Vehicle[] MyVehicles; }
public int NestingLevel {get; set;}
|
When applying the attribute, specify which hierarchy level the attribute affects by setting the XmlArrayItemAttribute.NestingLevel. The first index always has the value of zero; therefore it is optional to set its XmlArrayItemAttribute.NestingLevel --an XmlArrayItemAttribute without a XmlArrayItemAttribute.NestingLevel value will be applied to the first array index. Only the subsequent XmlArrayItemAttribute objects need XmlArrayItemAttribute.NestingLevel values specified (as 1, 2, 3, and so forth).
using System; using System.Xml; using System.Xml.Serialization; using System.IO; public class Forest{ /* Set the NestingLevel for each array. The first attribute (NestingLevel = 0) is optional. */ [XmlArrayItem(ElementName = "tree", NestingLevel = 0)] [XmlArrayItem(ElementName = "branch", NestingLevel = 1)] [XmlArrayItem(ElementName = "leaf",NestingLevel = 2)] public string[][][] TreeArray; } public class Test{ public static void Main(){ Test t = new Test(); t.SerializeObject("Tree.xml"); } private void SerializeObject(string filename){ XmlSerializer serializer = new XmlSerializer(typeof(Forest)); Forest f = new Forest(); string[][][] myTreeArray = new string[2] [][]; string[][]myBranchArray1= new string[1][]; myBranchArray1[0]=new string[1]{"One"}; myTreeArray[0]=myBranchArray1; string[][]myBranchArray2= new string[2][]; myBranchArray2[0]=new string[2]{"One","Two"}; myBranchArray2[1]=new string[3]{"One","Two","Three"}; myTreeArray[1]=myBranchArray2; f.TreeArray=myTreeArray; serializer.Serialize(Console.Out, f); } }
public Type Type {get; set;}
|
If a field or property returns an array of type Object, apply multiple instances of the XmlArrayItemAttribute to the field or property. For each instance, set the XmlElementAttribute.Type property to a type of object that can be inserted into the array.
If an array contains only primitive types, you need not apply the XmlArrayItemAttribute. By default, the XmlSerializer will generate a series of elements, each with the same element name, for each value, but the type of each element will be set to the XML Schema data type. For example, the following code:
' Visual Basic code Public Class Arrays Public XSDTypes ()As Object= New Object(){"one", 2, 3.0} End Class // C# code public class MyArray{ // No XmlArrayItemAttribute is applied. public object[] XSDTypes= new object[]{"one", 2, 3.2}; }
will result in this XML:
<?xml version="1.0" encoding="utf-8"?> <Arrays xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <XSDTypes> <Object xsi:type="xsd:string">one</Object> <Object xsi:type="xsd:int">2</Object> <Object xsi:type="xsd:double">3</Object> </XSDTypes> </Arrays>
However, if you specify the XmlArrayItemAttribute.Type property for each primitive type, the element name for each value will be generated using the .NET type name. For example this code:
' Visual Basic code Public Class Arrays <XmlArrayItem(GetType(String)), _ XmlArrayItem(GetType(Integer)), _ XmlArrayItem(GetType(Double))> _ Public PrimitiveTypes () As Object = New Object(){"one", 2, 3.0} End Class // C# code public class Arrays{ [XmlArrayItem(typeof(string))] [XmlArrayItem(typeof(int))] [XmlArrayItem(typeof(double))] public object [] PrimitiveTypes = new object[]{"one", 2, 3.0}; }
will result in this XML:
<?xml version="1.0" encoding="utf-8"?> <Arrays xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <PrimitiveTypes> <string>one</string> <int>2</int> <double>3</double> </PrimitiveTypes> </Arrays>
using System; using System.IO; using System.Xml.Serialization; public class Group { /* The Type property instructs the XmlSerializer to accept both the Person and Manager types in the array. */ [XmlArrayItem(Type = typeof(Manager)), XmlArrayItem(Type=typeof(Person))] public Person[]Staff; } public class Person { public string Name; } public class Manager:Person { public int Rank; } public class Run { public static void Main() { Run test = new Run(); test.SerializeOrder("TypeEx.xml"); } public void SerializeOrder(string filename) { // Create an XmlSerializer instance. XmlSerializer xSer = new XmlSerializer(typeof(Group)); // Create the Group object, and two array items. Group myGroup = new Group(); Person p1 = new Person(); p1.Name = "Jacki"; Manager p2 = new Manager(); p2.Name = "Megan"; p2.Rank = 2; Person [] myStaff = {p1,p2}; myGroup.Staff = myStaff; // Serialize the object, and close the StreamWriter. TextWriter writer = new StreamWriter(filename); xSer.Serialize(writer, myGroup); } }
public virtual object TypeId {get;}
|
~XmlArrayItemAttribute(); |
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(); |