XmlArrayItemAttribute Constructor (Type^)
Initializes a new instance of the XmlArrayItemAttribute class and specifies the Type that can be inserted into the serialized array.
Assembly: System.Xml (in System.Xml.dll)
The following example serializes a class named Transportation that 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 Type property using the type parameter.
#using <System.Xml.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Serialization; public ref class Vehicle { public: String^ id; }; public ref class Car: public Vehicle { public: String^ Maker; }; public ref class Transportation { public: [XmlArrayItem(Vehicle::typeid), XmlArrayItem(Car::typeid)] array<Vehicle^>^MyVehicles; }; void SerializeObject( String^ filename ) { // Creates an XmlSerializer. XmlSerializer^ MySerializer = gcnew XmlSerializer( Transportation::typeid ); // Writing the XML file to disk requires a TextWriter. TextWriter^ myTextWriter = gcnew StreamWriter( filename ); Transportation^ myTransportation = gcnew Transportation; Vehicle^ myVehicle = gcnew Vehicle; myVehicle->id = "A12345"; Car^ myCar = gcnew Car; myCar->id = "Car 34"; myCar->Maker = "FamousCarMaker"; array<Vehicle^>^myVehicles = {myVehicle,myCar}; myTransportation->MyVehicles = myVehicles; // Serializes the object, and closes the StreamWriter. MySerializer->Serialize( myTextWriter, myTransportation ); myTextWriter->Close(); } void DeserializeObject( String^ filename ) { // Creates the serializer with the type to deserialize. XmlSerializer^ mySerializer = gcnew XmlSerializer( Transportation::typeid ); FileStream^ myFileStream = gcnew FileStream( filename,FileMode::Open ); Transportation^ myTransportation = dynamic_cast<Transportation^>(mySerializer->Deserialize( myFileStream )); for ( int i = 0; i < myTransportation->MyVehicles->Length; i++ ) { Console::WriteLine( myTransportation->MyVehicles[ i ]->id ); } } int main() { SerializeObject( "XmlArrayItem3.xml" ); DeserializeObject( "XmlArrayItem3.xml" ); }
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1