XmlSerializer クラス

定義

オブジェクトから XML ドキュメントへのシリアル化および XML ドキュメントからオブジェクトへの逆シリアル化を実行します。 XmlSerializer により、オブジェクトを XML にエンコードする方法を制御できます。

public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
継承
XmlSerializer

次の例には、 と の 2 つの主要なクラスが PurchaseOrderTest含まれています。 クラスには PurchaseOrder 、1 回の購入に関する情報が含まれています。 Testクラスには、発注書を作成し、作成された発注書を読み取るメソッドが含まれています。

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;
ref class Address;
ref class OrderedItem;

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element namespace; by 
   default, the XmlSerializer uses the class name. The attribute 
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether 
   the xsi:null attribute appears if the class instance is set to 
   a null reference. */

[XmlRootAttribute("PurchaseOrder",Namespace="http://www.cpandl.com",
IsNullable=false)]
public ref class PurchaseOrder
{
public:
   Address^ ShipTo;
   String^ OrderDate;

   /* The XmlArrayAttribute changes the XML element name
       from the default of "OrderedItems" to "Items". */

   [XmlArrayAttribute("Items")]
   array<OrderedItem^>^OrderedItems;
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;
};

public ref class Address
{
public:

   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
         field as an XML attribute instead of an XML element (the default
         behavior). */

   [XmlAttributeAttribute]
   String^ Name;
   String^ Line1;

   /* Setting the IsNullable property to false instructs the 
         XmlSerializer that the XML attribute will not appear if 
         the City field is set to a null reference. */

   [XmlElementAttribute(IsNullable=false)]
   String^ City;
   String^ State;
   String^ Zip;
};

public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
         and stores the value in a field. */
   void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }

};

public ref class Test
{
public:
   static void main()
   {
      // Read and write purchase orders.
      Test^ t = gcnew Test;
      t->CreatePO( "po.xml" );
      t->ReadPO( "po.xml" );
   }

private:
   void CreatePO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );
      TextWriter^ writer = gcnew StreamWriter( filename );
      PurchaseOrder^ po = gcnew PurchaseOrder;

      // Create an address to ship and bill to.
      Address^ billAddress = gcnew Address;
      billAddress->Name = "Teresa Atkinson";
      billAddress->Line1 = "1 Main St.";
      billAddress->City = "AnyTown";
      billAddress->State = "WA";
      billAddress->Zip = "00000";

      // Set ShipTo and BillTo to the same addressee.
      po->ShipTo = billAddress;
      po->OrderDate = System::DateTime::Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem^ i1 = gcnew OrderedItem;
      i1->ItemName = "Widget S";
      i1->Description = "Small widget";
      i1->UnitPrice = (Decimal)5.23;
      i1->Quantity = 3;
      i1->Calculate();

      // Insert the item into the array.
      array<OrderedItem^>^items = {i1};
      po->OrderedItems = items;

      // Calculate the total cost.
      Decimal subTotal = Decimal(0);
      System::Collections::IEnumerator^ myEnum = items->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum->Current);
         subTotal = subTotal + oi->LineTotal;
      }

      po->SubTotal = subTotal;
      po->ShipCost = (Decimal)12.51;
      po->TotalCost = po->SubTotal + po->ShipCost;

      // Serialize the purchase order, and close the TextWriter.
      serializer->Serialize( writer, po );
      writer->Close();
   }

protected:
   void ReadPO( String^ filename )
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer^ serializer = gcnew XmlSerializer( PurchaseOrder::typeid );

      /* If the XML document has been altered with unknown 
            nodes or attributes, handle them with the 
            UnknownNode and UnknownAttribute events.*/
      serializer->UnknownNode += gcnew XmlNodeEventHandler( this, &Test::serializer_UnknownNode );
      serializer->UnknownAttribute += gcnew XmlAttributeEventHandler( this, &Test::serializer_UnknownAttribute );

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew 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 = dynamic_cast<PurchaseOrder^>(serializer->Deserialize( fs ));

      // Read the order date.
      Console::WriteLine( "OrderDate: {0}", po->OrderDate );

      // Read the shipping address.
      Address^ shipTo = po->ShipTo;
      ReadAddress( shipTo, "Ship To:" );

      // Read the list of ordered items.
      array<OrderedItem^>^items = po->OrderedItems;
      Console::WriteLine( "Items to be shipped:" );
      System::Collections::IEnumerator^ myEnum1 = items->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum1->Current);
         Console::WriteLine( "\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, oi->UnitPrice, oi->Quantity, oi->LineTotal );
      }

      Console::WriteLine( "\t\t\t\t\t Subtotal\t{0}", po->SubTotal );
      Console::WriteLine( "\t\t\t\t\t Shipping\t{0}", po->ShipCost );
      Console::WriteLine( "\t\t\t\t\t Total\t\t{0}", po->TotalCost );
   }

   void ReadAddress( Address^ a, String^ label )
   {
      // Read the fields of the Address object.
      Console::WriteLine( label );
      Console::WriteLine( "\t{0}", a->Name );
      Console::WriteLine( "\t{0}", a->Line1 );
      Console::WriteLine( "\t{0}", a->City );
      Console::WriteLine( "\t{0}", a->State );
      Console::WriteLine( "\t{0}", a->Zip );
      Console::WriteLine();
   }

private:
   void serializer_UnknownNode( Object^ /*sender*/, XmlNodeEventArgs^ e )
   {
      Console::WriteLine( "Unknown Node:{0}\t{1}", e->Name, e->Text );
   }

   void serializer_UnknownAttribute( Object^ /*sender*/, XmlAttributeEventArgs^ e )
   {
      System::Xml::XmlAttribute^ attr = e->Attr;
      Console::WriteLine( "Unknown attribute {0}='{1}'", attr->Name, attr->Value );
   }
};

int main()
{
   Test::main();
}
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

/* The XmlRootAttribute allows you to set an alternate name
   (PurchaseOrder) of the XML element, the element namespace; by
   default, the XmlSerializer uses the class name. The attribute
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether
   the xsi:null attribute appears if the class instance is set to
   a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
   public Address ShipTo;
   public string OrderDate;
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   [XmlArrayAttribute("Items")]
   public OrderedItem[] OrderedItems;
   public decimal SubTotal;
   public decimal ShipCost;
   public decimal TotalCost;
}

public class Address
{
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
   [XmlAttribute]
   public string Name;
   public string Line1;

   /* Setting the IsNullable property to false instructs the
      XmlSerializer that the XML attribute will not appear if
      the City field is set to a null reference. */
   [XmlElementAttribute(IsNullable = false)]
   public string City;
   public string State;
   public string Zip;
}

public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.CreatePO("po.xml");
      t.ReadPO("po.xml");
   }

   private void CreatePO(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);
      PurchaseOrder po=new PurchaseOrder();

      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();

      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51;
      po.TotalCost = po.SubTotal + po.ShipCost;
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }

   protected void ReadPO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
      /* If the XML document has been altered with unknown
      nodes or attributes, handle them with the
      UnknownNode and UnknownAttribute events.*/
      serializer.UnknownNode+= new
      XmlNodeEventHandler(serializer_UnknownNode);
      serializer.UnknownAttribute+= new
      XmlAttributeEventHandler(serializer_UnknownAttribute);

      // 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);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);

      // Read the shipping address.
      Address shipTo = po.ShipTo;
      ReadAddress(shipTo, "Ship To:");
      // Read the list of ordered items.
      OrderedItem [] items = po.OrderedItems;
      Console.WriteLine("Items to be shipped:");
      foreach(OrderedItem oi in items)
      {
         Console.WriteLine("\t"+
         oi.ItemName + "\t" +
         oi.Description + "\t" +
         oi.UnitPrice + "\t" +
         oi.Quantity + "\t" +
         oi.LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
      Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
      Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
   }

   protected void ReadAddress(Address a, string label)
   {
      // Read the fields of the Address object.
      Console.WriteLine(label);
      Console.WriteLine("\t"+ a.Name );
      Console.WriteLine("\t" + a.Line1);
      Console.WriteLine("\t" + a.City);
      Console.WriteLine("\t" + a.State);
      Console.WriteLine("\t" + a.Zip );
      Console.WriteLine();
   }

   private void serializer_UnknownNode
   (object sender, XmlNodeEventArgs e)
   {
      Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
   }

   private void serializer_UnknownAttribute
   (object sender, XmlAttributeEventArgs e)
   {
      System.Xml.XmlAttribute attr = e.Attr;
      Console.WriteLine("Unknown attribute " +
      attr.Name + "='" + attr.Value + "'");
   }
}
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO

' The XmlRootAttribute allows you to set an alternate name
' (PurchaseOrder) of the XML element, the element namespace; by
' default, the XmlSerializer uses the class name. The attribute
' also allows you to set the XML namespace for the element.  Lastly,
' the attribute sets the IsNullable property, which specifies whether
' the xsi:null attribute appears if the class instance is set to
' a null reference. 
<XmlRootAttribute("PurchaseOrder", _
 Namespace := "http://www.cpandl.com", IsNullable := False)> _
Public Class PurchaseOrder
    
    Public ShipTo As Address
    Public OrderDate As String
    ' The XmlArrayAttribute changes the XML element name
    ' from the default of "OrderedItems" to "Items". 
    <XmlArrayAttribute("Items")> _
    Public OrderedItems() As OrderedItem
    Public SubTotal As Decimal
    Public ShipCost As Decimal
    Public TotalCost As Decimal
End Class


Public Class Address
    ' The XmlAttribute instructs the XmlSerializer to serialize the Name
    ' field as an XML attribute instead of an XML element (the default
    ' behavior). 
    <XmlAttribute()> _
    Public Name As String
    Public Line1 As String
    
    ' Setting the IsNullable property to false instructs the
    ' XmlSerializer that the XML attribute will not appear if
    ' the City field is set to a null reference. 
    <XmlElementAttribute(IsNullable := False)> _
    Public City As String
    Public State As String
    Public Zip As String
End Class


Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
    Public LineTotal As Decimal
    
    
    ' Calculate is a custom method that calculates the price per item,
    ' and stores the value in a field. 
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
   Public Shared Sub Main()
      ' Read and write purchase orders.
      Dim t As New Test()
      t.CreatePO("po.xml")
      t.ReadPO("po.xml")
   End Sub
    
   Private Sub CreatePO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to serialize.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      Dim writer As New StreamWriter(filename)
      Dim po As New PurchaseOrder()
        
      ' Create an address to ship and bill to.
      Dim billAddress As New Address()
      billAddress.Name = "Teresa Atkinson"
      billAddress.Line1 = "1 Main St."
      billAddress.City = "AnyTown"
      billAddress.State = "WA"
      billAddress.Zip = "00000"
      ' Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress
      po.OrderDate = System.DateTime.Now.ToLongDateString()
        
      ' Create an OrderedItem object.
      Dim i1 As New OrderedItem()
      i1.ItemName = "Widget S"
      i1.Description = "Small widget"
      i1.UnitPrice = CDec(5.23)
      i1.Quantity = 3
      i1.Calculate()
        
      ' Insert the item into the array.
      Dim items(0) As OrderedItem
      items(0) = i1
      po.OrderedItems = items
      ' Calculate the total cost.
      Dim subTotal As New Decimal()
      Dim oi As OrderedItem
      For Each oi In  items
         subTotal += oi.LineTotal
      Next oi
      po.SubTotal = subTotal
      po.ShipCost = CDec(12.51)
      po.TotalCost = po.SubTotal + po.ShipCost
      ' Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po)
      writer.Close()
   End Sub
    
   Protected Sub ReadPO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to be deserialized.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      ' If the XML document has been altered with unknown
      ' nodes or attributes, handle them with the
      ' UnknownNode and UnknownAttribute events.
      AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
      AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute
      
      ' A FileStream is needed to read the XML document.
      Dim fs As New FileStream(filename, FileMode.Open)
      ' Declare an object variable of the type to be deserialized.
      Dim po As PurchaseOrder
      ' Use the Deserialize method to restore the object's state with
      ' data from the XML document. 
      po = CType(serializer.Deserialize(fs), PurchaseOrder)
      ' Read the order date.
      Console.WriteLine(("OrderDate: " & po.OrderDate))
        
      ' Read the shipping address.
      Dim shipTo As Address = po.ShipTo
      ReadAddress(shipTo, "Ship To:")
      ' Read the list of ordered items.
      Dim items As OrderedItem() = po.OrderedItems
      Console.WriteLine("Items to be shipped:")
      Dim oi As OrderedItem
      For Each oi In  items
         Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _
         oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _
         oi.Quantity & ControlChars.Tab & oi.LineTotal))
      Next oi
      ' Read the subtotal, shipping cost, and total cost.
      Console.WriteLine(( New String(ControlChars.Tab, 5) & _
      " Subtotal"  & ControlChars.Tab & po.SubTotal))
      Console.WriteLine(New String(ControlChars.Tab, 5) & _
      " Shipping" & ControlChars.Tab & po.ShipCost )
      Console.WriteLine( New String(ControlChars.Tab, 5) & _
      " Total" &  New String(ControlChars.Tab, 2) & po.TotalCost)
    End Sub
    
    Protected Sub ReadAddress(a As Address, label As String)
      ' Read the fields of the Address object.
      Console.WriteLine(label)
      Console.WriteLine(ControlChars.Tab & a.Name)
      Console.WriteLine(ControlChars.Tab & a.Line1)
      Console.WriteLine(ControlChars.Tab & a.City)
      Console.WriteLine(ControlChars.Tab & a.State)
      Console.WriteLine(ControlChars.Tab & a.Zip)
      Console.WriteLine()
    End Sub
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub
    
    
    Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs)
        Dim attr As System.Xml.XmlAttribute = e.Attr
        Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'"))
    End Sub
End Class

注釈

XML シリアル化とは、オブジェクトのパブリック プロパティとパブリック フィールドを格納したり伝送できるようにシリアル形式 (この場合は XML) に変換する処理のことです。 逆シリアル化により、XML 出力から元の状態のオブジェクトが再作成されます。 シリアル化は、オブジェクトの状態をストリームまたはバッファーに保存する方法と考えることができます。 たとえば、ASP.NET は クラスを XmlSerializer 使用して XML Web サービス メッセージをエンコードします。

オブジェクトのデータは、クラス、フィールド、プロパティ、プリミティブ型、配列などのプログラミング構成要素、および XmlElement オブジェクトまたは XmlAttribute オブジェクトの形で埋め込まれている XML を使用して記述されます。 独自のクラスを作成したり、属性で注釈を付けたり、 XML スキーマ定義ツール (Xsd.exe) を使用して、既存の XML スキーマ定義 (XSD) ドキュメントに基づいてクラスを生成したりすることができます。 XML スキーマがある場合は、Xsd.exeを実行して、スキーマに厳密に型指定され、シリアル化時にスキーマに準拠する属性で注釈が付けられたクラスのセットを生成できます。

オブジェクトと XML の間でデータを転送するには、プログラミング言語コンストラクトから XML スキーマ、および XML スキーマからプログラミング言語コンストラクトへのマッピングが必要です。 Xsd.exeなどのおよび関連ツールは XmlSerializer 、設計時と実行時の両方でこれら 2 つのテクノロジ間の橋渡しを提供します。 デザイン時に、Xsd.exeを使用して、カスタム クラスから XML スキーマ ドキュメント (.xsd) を生成するか、特定のスキーマからクラスを生成します。 どちらの場合も、XML スキーマ システムと共通言語ランタイムの間でマップする方法を指示 XmlSerializer するために、クラスにカスタム属性で注釈が付けられます。 実行時に、クラスのインスタンスを、指定されたスキーマに従う XML ドキュメントにシリアル化できます。 同様に、これらの XML ドキュメントはランタイム オブジェクトに逆シリアル化できます。 XML スキーマは省略可能であり、デザイン時または実行時には必要ありません。

生成された XML を制御する

生成された XML を制御するために、クラスとメンバーに特別な属性を適用できます。 たとえば、別の XML 要素名を指定するには、 を XmlElementAttribute パブリック フィールドまたはプロパティに適用し、 プロパティを設定します ElementName 。 類似する属性の完全な一覧については、「 XML シリアル化を制御する属性」を参照してください。 また、 インターフェイスを IXmlSerializable 実装して XML 出力を制御することもできます。

生成された XML が World Wide Consortium ドキュメントのセクション 5 である Simple Object Access Protocol (SOAP) 1.1 に準拠している必要がある場合は、 を使用XmlTypeMappingして をXmlSerializer構築する必要があります。 エンコードされた SOAP XML をさらに制御するには、「エンコードされた SOAP シリアル化を制御する属性」に記載されている属性を使用します。

XmlSerializer 使用すると、厳密に型指定されたクラスの操作を利用でき、XML の柔軟性を引き続き利用できます。 型XmlElementXmlAttributeのフィールドまたはプロパティ、またはXmlNode厳密に型指定されたクラスを使用して、XML ドキュメントの一部を XML オブジェクトに直接読み取ることができます。

拡張 XML スキーマを使用する場合は、 属性と XmlAnyAttributeAttribute 属性を使用XmlAnyElementAttributeして、元のスキーマに見つからない要素または属性をシリアル化および逆シリアル化することもできます。 オブジェクトを使用するには、オブジェクトの配列を返すフィールドに を適用XmlAnyElementAttributeするか、オブジェクトのXmlElement配列XmlAttributeを返すフィールドに を適用XmlAnyAttributeAttributeします。

プロパティやフィールドが複雑なオブジェクト (配列やクラス インスタンスなど) を返す場合、XmlSerializer は、そのオブジェクトを、メイン XML ドキュメント内で入れ子になっている要素に変換します。 たとえば、次のコードの最初のクラスは、2 番目のクラスのインスタンスを返します。

Public Class MyClass  
    Public MyObjectProperty As MyObject  
End Class  

Public Class MyObject  
    Public ObjectName As String  
End Class  
public class MyClass  
{  
    public MyObject MyObjectProperty;  
}  
public class MyObject  
{  
    public string ObjectName;  
}  

シリアル化された XML 出力は次のようになります。

<MyClass>  
  <MyObjectProperty>  
  <ObjectName>My String</ObjectName>  
  </MyObjectProperty>  
</MyClass>  

スキーマに省略可能な要素 (minOccurs = '0') が含まれている場合、またはスキーマに既定値が含まれている場合は、2 つのオプションがあります。 1 つのオプションは、次のコードに示すように、 を使用 System.ComponentModel.DefaultValueAttribute して既定値を指定することです。

Public Class PurchaseOrder  
    <System.ComponentModel.DefaultValueAttribute ("2002")> _  
    Public Year As String  
End Class  
public class PurchaseOrder  
{  
    [System.ComponentModel.DefaultValueAttribute ("2002")]  
    public string Year;  
}  

もう 1 つのオプションは、特殊なパターンを使用して、 で認識されるブール型フィールドを XmlSerializer作成し、 をフィールドに適用 XmlIgnoreAttribute することです。 パターンは、 の形式 propertyNameSpecifiedで作成されます。 たとえば、"MyFirstName" という名前のフィールドがある場合は、"MyFirstName" という名前の XML 要素を生成するかどうかを指示 XmlSerializer する "MyFirstNameSpecified" という名前のフィールドも作成します。 次の例を参照してください。

Public Class OptionalOrder  
    ' This field's value should not be serialized   
    ' if it is uninitialized.  
    Public FirstOrder As String  

    ' Use the XmlIgnoreAttribute to ignore the   
    ' special field named "FirstOrderSpecified".  
    <System.Xml.Serialization.XmlIgnoreAttribute> _  
    Public FirstOrderSpecified As Boolean  
End Class  
public class OptionalOrder  
{  
    // This field should not be serialized   
    // if it is uninitialized.  
    public string FirstOrder;  

    // Use the XmlIgnoreAttribute to ignore the   
    // special field named "FirstOrderSpecified".  
    [System.Xml.Serialization.XmlIgnoreAttribute]  
    public bool FirstOrderSpecified;  
}  

既定のシリアル化をオーバーライドする

適切な属性の 1 つを作成し、 クラスのインスタンスに追加することで、オブジェクトのセットとそのフィールドとプロパティの XmlAttributes シリアル化をオーバーライドすることもできます。 この方法でシリアル化をオーバーライドすると、2 つの用途があります。最初に、ソースにアクセスできない場合でも、DLL で見つかったオブジェクトのシリアル化を制御および拡張できます。2 つ目は、シリアル化可能なクラスのセットを 1 つ作成できますが、複数の方法でオブジェクトをシリアル化できます。 詳細については、「クラス」および「方法: 派生クラスのシリアル化を制御する」を参照してくださいXmlAttributeOverrides

オブジェクトをシリアル化するには、 メソッドを Serialize 呼び出します。 オブジェクトを逆シリアル化するには、 メソッドを Deserialize 呼び出します。

XML ドキュメントに XML 名前空間を追加するには、「」を参照してください XmlSerializerNamespaces

Note

XmlSerializer、 または ICollectionを実装IEnumerableするクラスに特別な処理を提供します。 IEnumerable を実装するクラスは、単一のパラメーターを受け取るパブリックな Add メソッドを実装している必要があります。 メソッドのパラメーターは Add 、 から返される値の プロパティから Current 返される GetEnumeratorのと同じ型であるか、またはその型の基底のいずれかである必要があります。 に加えて ( などCollectionBase) をIEnumerable実装ICollectionするクラスには、整数を受け取るパブリック Item インデックス付きプロパティ (C#のインデクサー) があり、整数型のパブリック Count プロパティが必要です。 メソッドの Add パラメーターは、 プロパティから Item 返されるのと同じ型であるか、その型の基底のいずれかである必要があります。 を実装ICollectionするクラスの場合、シリアル化される値は、 を呼び出GetEnumeratorすことによってではなく、インデックス付きItemプロパティから取得されます。

オブジェクトを逆シリアル化するには、(TEMP 環境変数で定義されている) 一時ディレクトリに書き込む権限が必要です。

動的に生成されたアセンブリ

パフォーマンスを向上させるために、XML シリアル化インフラストラクチャは、指定された型をシリアル化および逆シリアル化するアセンブリを動的に生成します。 インフラストラクチャは、これらのアセンブリを見つけて再利用します。 この動作は、次のコンストラクターを使用する場合にのみ発生します。

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

他のコンストラクターのいずれかを使用すると、同じアセンブリの複数のバージョンが生成され、アンロードされることはありません。これにより、メモリ リークが発生し、パフォーマンスが低下します。 最も簡単な解決策は、前述の 2 つのコンストラクターのいずれかを使用することです。 それ以外の場合は、次の例に示すように、アセンブリを Hashtableにキャッシュする必要があります。

Hashtable serializers = new Hashtable();  

// Use the constructor that takes a type and XmlRootAttribute.  
XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);  

// Implement a method named GenerateKey that creates unique keys   
// for each instance of the XmlSerializer. The code should take   
// into account all parameters passed to the XmlSerializer   
// constructor.  
object key = GenerateKey(typeof(MyClass), myRoot);  

// Check the local cache for a matching serializer.  
XmlSerializer ser = (XmlSerializer)serializers[key];  
if (ser == null)   
{  
    ser = new XmlSerializer(typeof(MyClass), myRoot);  
    // Cache the serializer.  
    serializers[key] = ser;  
}

// Use the serializer to serialize or deserialize.
Dim serializers As New Hashtable()  

' Use the constructor that takes a type and XmlRootAttribute.  
Dim s As New XmlSerializer(GetType([MyClass]), myRoot)  

' Implement a method named GenerateKey that creates unique keys   
' for each instance of the XmlSerializer. The code should take   
' into account all parameters passed to the XmlSerializer   
' constructor.  
Dim key As Object = GenerateKey(GetType([MyClass]), myRoot)  

' Check the local cache for a matching serializer.  
Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer)  

If ser Is Nothing Then  
    ser = New XmlSerializer(GetType([MyClass]), myRoot)  
    ' Cache the serializer.  
    serializers(key) = ser  
End If  

' Use the serializer to serialize or deserialize.

ArrayList とジェネリック リストのシリアル化

では XmlSerializer 、次のコードをシリアル化または逆シリアル化できません。

符号なし Long の列挙体のシリアル化

XmlSerializer次の条件が満たされている場合は、 をインスタンス化して列挙体をシリアル化できません。列挙体は unsigned long 型 (ulongC# では ) で、列挙体には 9,223,372,036,854,775,807 より大きい値を持つメンバーが含まれています。 たとえば、次のコードはシリアル化できません。

public enum LargeNumbers: ulong  
{  
    a = 9223372036854775808  
}  
// At runtime, the following code will fail.  
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));  

Obsolete 属性でマークされたオブジェクトはシリアル化されなくなりました

.NET Framework 3.5 以降では、 XmlSerializer クラスは として[Obsolete]マークされているオブジェクトをシリアル化しなくなりました。

コンストラクター

XmlSerializer()

XmlSerializer クラスの新しいインスタンスを初期化します。

XmlSerializer(Type)

指定した型のオブジェクトを XML ドキュメントにシリアル化したり、XML ドキュメントを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。

XmlSerializer(Type, String)

指定した型のオブジェクトを XML ドキュメントにシリアル化したり、XML ドキュメントを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 すべての XML 要素の既定の名前空間を指定します。

XmlSerializer(Type, Type[])

指定した型のオブジェクトを XML ドキュメントにシリアル化したり、XML ドキュメントを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 プロパティまたはフィールドが配列を返す場合、extraTypes パラメーターには、その配列に挿入できるオブジェクトを指定します。

XmlSerializer(Type, XmlAttributeOverrides)

指定した型のオブジェクトを XML ドキュメントにシリアル化したり、XML ドキュメントを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 シリアル化される各オブジェクトはそれ自体がクラスのインスタンスを含むことができ、それをこのオーバーロードによって他のクラスでオーバーライドします。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

Object 型のオブジェクトを XML ドキュメント インスタンスにシリアル化したり、XML ドキュメント インスタンスを Object 型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 シリアル化される各オブジェクトはそれ自体がクラスのインスタンスを含むことができ、それをこのオーバーロードによって他のクラスでオーバーライドします。 このオーバーロードでは、すべての XML 要素の既定の名前空間、および XML ルート要素として使用するクラスも指定します。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

Object 型のオブジェクトを XML ドキュメント インスタンスにシリアル化したり、XML ドキュメント インスタンスを Object 型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 シリアル化される各オブジェクトはそれ自体がクラスのインスタンスを含むことができ、それをこのオーバーロードによって他のクラスでオーバーライドします。 このオーバーロードでは、すべての XML 要素の既定の名前空間、および XML ルート要素として使用するクラスも指定します。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
互換性のために残されています。

指定した型のオブジェクトを XML ドキュメント インスタンスにシリアル化したり、XML ドキュメント インスタンスを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 このオーバーロードでは、シリアル化操作または逆シリアル化操作で見つかる可能性がある他の型、すべての XML 要素の既定の名前空間、XML ルート要素として使用されるクラスとその場所、およびアクセスで要求される資格情報を提供できます。

XmlSerializer(Type, XmlRootAttribute)

指定した型のオブジェクトを XML ドキュメントにシリアル化したり、XML ドキュメントを指定した型のオブジェクトに逆シリアル化したりできる、XmlSerializer クラスの新しいインスタンスを初期化します。 また、XML ルート要素として使用するクラスを指定します。

XmlSerializer(XmlTypeMapping)

ある型を別の型にマップするオブジェクトを指定して、XmlSerializer クラスのインスタンスを初期化します。

メソッド

CanDeserialize(XmlReader)

XmlSerializer が、指定された XML ドキュメントを逆シリアル化できるかどうかを示す値を取得します。

CreateReader()

シリアル化される XML ドキュメントを読み取るために使用されるオブジェクトを返します。

CreateWriter()

派生クラスでオーバーライドされた場合、オブジェクトのシリアル化に使用されるライターを返します。

Deserialize(Stream)

指定した Stream に格納されている XML ドキュメントを逆シリアル化します。

Deserialize(TextReader)

指定した TextReader に格納されている XML ドキュメントを逆シリアル化します。

Deserialize(XmlReader)

指定した XmlReader に格納されている XML ドキュメントを逆シリアル化します。

Deserialize(XmlReader, String)

指定した XmlReader に格納されている XML ドキュメントを、指定したエンコード スタイルを使用して逆シリアル化します。

Deserialize(XmlReader, String, XmlDeserializationEvents)

指定した XmlReader に格納されているデータを使用してオブジェクトを逆シリアル化します。

Deserialize(XmlReader, XmlDeserializationEvents)

指定した XmlReader に格納されている XML ドキュメントを逆シリアル化します。また、逆シリアル化で発生するイベントのオーバーライドを可能にします。

Deserialize(XmlSerializationReader)

指定した XmlSerializationReader に格納されている XML ドキュメントを逆シリアル化します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
FromMappings(XmlMapping[])

XmlTypeMapping オブジェクトの配列から作成された、XmlSerializer オブジェクトの配列を返します。

FromMappings(XmlMapping[], Evidence)
互換性のために残されています。

XML 型から別の型への割り当てから作成された XmlSerializer クラスのインスタンスを返します。

FromMappings(XmlMapping[], Type)

指定したマッピングから XmlSerializer クラスのインスタンスを返します。

FromTypes(Type[])

型の配列から作成された、XmlSerializer オブジェクトの配列を返します。

GenerateSerializer(Type[], XmlMapping[])

指定した割り当てを使用して、指定した型をシリアル化または逆シリアル化するために使用される、カスタム シリアライザーを格納しているアセンブリを返します。

GenerateSerializer(Type[], XmlMapping[], CompilerParameters)

指定した割り当てとコンパイラの設定およびオプションを使用して、指定した型をシリアル化または逆シリアル化するために使用される、カスタム シリアライザーを格納しているアセンブリを返します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
GetXmlSerializerAssemblyName(Type)

指定した型のシリアル化または逆シリアル化のために特に作成された、1 つ以上のバージョンの XmlSerializer を格納しているアセンブリの名前を返します。

GetXmlSerializerAssemblyName(Type, String)

指定した名前空間にある指定した型のシリアライザーを格納しているアセンブリの名前を返します。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
Serialize(Object, XmlSerializationWriter)

指定した Object をシリアル化し、生成された XML ドキュメントを、指定した XmlSerializationWriter を使用してファイルに書き込みます。

Serialize(Stream, Object)

指定した Object をシリアル化し、生成された XML ドキュメントを、指定した Stream を使用してファイルに書き込みます。

Serialize(Stream, Object, XmlSerializerNamespaces)

指定した Object をシリアル化し、指定した Stream を使用して、指定した名前空間を参照し、生成された XML ドキュメントをファイルに書き込みます。

Serialize(TextWriter, Object)

指定した Object をシリアル化し、生成された XML ドキュメントを、指定した TextWriter を使用してファイルに書き込みます。

Serialize(TextWriter, Object, XmlSerializerNamespaces)

指定した Object をシリアル化し、指定した TextWriter を使用して XML ドキュメントをファイルに書き込み、指定した名前空間を参照します。

Serialize(XmlWriter, Object)

指定した Object をシリアル化し、生成された XML ドキュメントを、指定した XmlWriter を使用してファイルに書き込みます。

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

指定した Object をシリアル化し、指定した XmlWriter を使用して XML ドキュメントをファイルに書き込み、指定した名前空間を参照します。

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

指定したオブジェクトをシリアル化し、指定した XmlWriter を使用して、指定した名前空間とエンコード スタイルを参照し、生成された XML ドキュメントをファイルに書き込みます。

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

指定した Object をシリアル化し、指定した XmlWriter、XML 名前空間、およびエンコーディングを使用して、XML ドキュメントをファイルに書き込みます。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

events

UnknownAttribute

逆シリアル化時に XmlSerializer が不明な型の XML 属性を認識した場合に発生します。

UnknownElement

逆シリアル化時に XmlSerializer が不明な型の XML 要素を認識した場合に発生します。

UnknownNode

逆シリアル化時に XmlSerializer が不明な型の XML ノードを認識した場合に発生します。

UnreferencedObject

SOAP エンコード済み XML ストリームの逆シリアル化時に、XmlSerializer が、未使用の型または参照されていない型を認識した場合に発生します。

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください