Export (0) Print
Expand All

XmlElementAttribute Constructor (String, Type)

.NET Framework 1.1

Initializes a new instance of the XmlElementAttribute; specifies the name of the XML element and a derived type for the member to which the XmlElementAttribute is applied, which is used when the XmlSerializer serializes a containing object.

[Visual Basic]
Public Sub New( _
   ByVal elementName As String, _
   ByVal type As Type _
)
[C#]
public XmlElementAttribute(
   string elementName,
 Type type
);
[C++]
public: XmlElementAttribute(
   String* elementName,
 Type* type
);
[JScript]
public function XmlElementAttribute(
   elementName : String,
 type : Type
);

Parameters

elementName
The XML element name of the serialized member.
type
The Type of an object derived from the member's type.

Remarks

By default, the XmlSerializer uses the member name as the XML element name when serializing a class instance. For example, a field named Vehicle generates an XML element named Vehicle. However, if you need a different element, such as Cars, pass it in the elementName parameter.

Use the type parameter to specify a type that is derived from a base class. For example, suppose a property named MyAnimal returns an Animal object. You want to enhance the object, so you create a new class named Mammal that inherits from the Animal class. To instruct the XmlSerializer to accept the Mammal class when it serializes the MyAnimal property, pass the Type of the Mammal class to the constructor.

Example

[Visual Basic, C#, C++] The following example serializes a class named Orchestra that contains a single field named Instruments, which returns an array of Instrument objects. A second class named Brass inherits from the Instrument class. The example applies the XmlElementAttribute to the Instruments field, and specifies the Brass type, allowing the Instruments field to accept Brass objects. The example also specifies the name of the XML element by setting the ElementName property.

[Visual Basic] 
Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml.Serialization
Imports Microsoft.VisualBasic


Public Class Orchestra
    Public Instruments() As Instrument
End Class

Public Class Instrument
    Public Name As String
End Class

Public Class Brass
    Inherits Instrument
    Public IsValved As Boolean
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Override.xml")
        test.DeserializeObject("Override.xml")
    End Sub 'Main
    
    
    Public Sub SerializeObject(filename As String)
        ' To write the file, a TextWriter is required.
        Dim writer As New StreamWriter(filename)
        
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Creates an XmlElementAttribute that overrides the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Adds the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Creates the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Creates the object to serialize.
        Dim band As New Orchestra()
        
        ' Creates an object of the derived type.
        Dim i As New Brass()
        i.Name = "Trumpet"
        i.IsValved = True
        Dim myInstruments() As Instrument = {i}
        band.Instruments = myInstruments
        s.Serialize(writer, band)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute that override the Instrument type.
        Dim attr As New XmlElementAttribute(GetType(Brass))
        attr.ElementName = "Brass"
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
        Console.WriteLine("Brass:")
        
        ' Deserializing differs from serializing. To read the
        ' derived-object values, declare an object of the derived
        ' type (Brass) and cast the Instrument instance to it. 
        Dim b As Brass
        Dim i As Instrument
        For Each i In  band.Instruments
            b = CType(i, Brass)
            Console.WriteLine((b.Name + ControlChars.Cr + b.IsValved.ToString()))
        Next i
    End Sub
End Class


[C#] 
using System;
using System.IO;
using System.Xml.Serialization;

public class Orchestra
{
   public Instrument[] Instruments;
}   

public class Instrument
{
   public string Name;
}

public class Brass:Instrument{
   public bool IsValved;
}

public class Run
{
    public static void Main()
    {
       Run test = new Run();
       test.SerializeObject("Override.xml");
       test.DeserializeObject("Override.xml");
    }

    public void SerializeObject(string filename)
    {
      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);
      
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that overrides the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Creates the object to serialize.
      Orchestra band = new Orchestra();
      
      // Creates an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Creates an XmlElementAttribute that override the Instrument type.
      XmlElementAttribute attr = new 
      XmlElementAttribute(typeof(Brass));
      attr.ElementName = "Brass";

      // Adds the element to the collection of elements.
      attrs.XmlElements.Add(attr);
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Creates the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s = 
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* Deserializing differs from serializing. To read the 
         derived-object values, declare an object of the derived 
         type (Brass) and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments) 
      {
         b= (Brass)i;
         Console.WriteLine(
         b.Name + "\n" + 
         b.IsValved);
      }
   }
}


[C++] 
#using <mscorlib.dll>
#using <System.Xml.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;

public __gc class Instrument
{
public:
   String* Name;
};

public __gc class Brass: public Instrument{
public:
   bool IsValved;
};

public __gc class Orchestra
{
public:
   Instrument* Instruments[];
};   

void SerializeObject(String* filename)
{
   // To write the file, a TextWriter is required.
   TextWriter* writer = new StreamWriter(filename);

   XmlAttributeOverrides* attrOverrides = 
      new XmlAttributeOverrides();
   XmlAttributes* attrs = new XmlAttributes();

   // Creates an XmlElementAttribute that overrides the Instrument type.
   XmlElementAttribute* attr = new 
      XmlElementAttribute(__typeof(Brass));
   attr->ElementName = S"Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add(attr);
   attrOverrides->Add(__typeof(Orchestra), S"Instruments", attrs);

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer* s = 
      new XmlSerializer(__typeof(Orchestra), attrOverrides);

   // Creates the object to serialize.
   Orchestra* band = new Orchestra();

   // Creates an object of the derived type.
   Brass* i = new Brass();
   i->Name = S"Trumpet";
   i->IsValved = true;
   Instrument* myInstruments[] = {i};
   band->Instruments = myInstruments;
   s->Serialize(writer,band);
   writer->Close();
}

void DeserializeObject(String* filename)
{
   XmlAttributeOverrides* attrOverrides = 
      new XmlAttributeOverrides();
   XmlAttributes* attrs = new XmlAttributes();

   // Creates an XmlElementAttribute that override the Instrument type.
   XmlElementAttribute* attr = new 
      XmlElementAttribute(__typeof(Brass));
   attr->ElementName = S"Brass";

   // Adds the element to the collection of elements.
   attrs->XmlElements->Add(attr);
   attrOverrides->Add(__typeof(Orchestra), S"Instruments", attrs);

   // Creates the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer* s = 
      new XmlSerializer(__typeof(Orchestra), attrOverrides);

   FileStream* fs = new FileStream(filename, FileMode::Open);
   Orchestra* band = dynamic_cast<Orchestra*> (s->Deserialize(fs));
   Console::WriteLine(S"Brass:");

   /* Deserializing differs from serializing. To read the 
   derived-object values, declare an object of the derived 
   type (Brass) and cast the Instrument instance to it. */
   Brass* b;
   System::Collections::IEnumerator* myEnum = band->Instruments->GetEnumerator();
   while (myEnum->MoveNext())
   {
      Instrument* i = __try_cast<Instrument*>(myEnum->Current);
      b = dynamic_cast<Brass*>(i);
      Console::WriteLine(S"{0}\n{1}", b->Name, __box(b->IsValved));
   }
}

int main()
{
   SerializeObject(S"Override.xml");
   DeserializeObject(S"Override.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

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

See Also

XmlElementAttribute Class | XmlElementAttribute Members | System.Xml.Serialization Namespace | XmlElementAttribute Constructor Overload List

Show:
© 2014 Microsoft