XmlSerializer クラス

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

この型のすべてのメンバの一覧については、XmlSerializer メンバ を参照してください。

System.Object
   System.Xml.Serialization.XmlSerializer

Public Class XmlSerializer
[C#]
public class XmlSerializer
[C++]
public __gc class XmlSerializer
[JScript]
public class XmlSerializer

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

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

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

オブジェクトと XML 間でデータを転送するには、プログラミング言語構成要素から XML スキーマへ、またはその逆への割り当てが必要です。 XmlSerializer や Xsd.exe などの関連ツールは、デザイン時および実行時に、これら 2 つの技術の間の処理を受け持ちます。デザイン時には、Xsd.exe を使用してカスタム クラスから XML スキーマ ドキュメント (.xsd) を作成するか、特定のスキーマからクラスを作成します。いずれの場合も、クラスにはカスタム属性を使用して注釈を付け、これによって XML スキーマ システムと共通言語ランタイム間の割り当てについて XmlSerializer に指示します。実行時には、クラスのインスタンスを、特定のスキーマに適合する XML ドキュメントにシリアル化できます。同様に、これらの XML ドキュメントをランタイム オブジェクトに逆シリアル化できます。XML スキーマはオプションであり、デザイン時または実行時に必ず用意する必要があるわけではありません。

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

生成される XML が、W3C (World Wide Web Consortium) (www.w3.org) のドキュメント『Simple Object Access Protocol (SOAP) 1.1』のセクション 5 に準拠している必要がある場合は、 XmlTypeMapping を使用して XmlSerializer を構築します。エンコード済みの SOAP XML をさらに制御するには、「 エンコード済み SOAP シリアル化を制御する属性 」の一覧に示されている属性を使用します。

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

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

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

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 を使用して既定値を指定する方法です。これを次の C# コードと Visual Basic コードに示します。

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

もう 1 つは、特殊パターンを使用して XmlSerializer が認識する Boolean フィールドを作成し、 XmlIgnoreAttribute をそのフィールドに適用する方法です。このパターンは propertyNameSpecified の形式で作成されます。たとえば、"MyFirstName" という名前のフィールドがある場合は、"MyFirstNameSpecified" というフィールドも作成して、"MyFirstName" という XML 要素を生成するかどうかを XmlSerializer に指示します。これを次の C# と Visual Basic の例に示します。

' Visual Basic
Public Class OptionalOrder
   ' This field's value shouldn't 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
' C#
public class OptionalOrder
{
   // This field shouldn't 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 内のオブジェクトのシリアル化を、そのソースにアクセスできなくても制御および強化できます。次に、複数のシリアル化可能なクラスをまとめて作成し、それらのオブジェクトを異なる方法でシリアル化できます。詳細については、 XmlAttributeOverrides クラスのトピックを参照してください。

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

XML ドキュメントに XML 名前空間を追加する方法については、 XmlSerializerNamespaces クラスのトピックを参照してください。

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

使用例

[Visual Basic, C#, C++] 2 つのメイン クラス、 PurchaseOrderTest が含まれている例を次に示します。 PurchaseOrder クラスには、1 件の購入に関する情報が格納されています。 Test クラスには発注書を作成するメソッドと、作成された発注書を読み取るメソッドが含まれています。

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


' 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 'PurchaseOrder


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 'Address


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 'Calculate
End Class 'OrderedItem


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 'Main
    
   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 'CreatePO
    
   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 'ReadPO
    
    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 'ReadAddress
        
    Protected Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub 'serializer_UnknownNode
    
    
    Protected 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 'serializer_UnknownAttribute
End Class 'Test

[C#] 
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();
   }

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

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

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

public __gc class Address;
public __gc 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(S"PurchaseOrder", Namespace=S"http://www.cpandl.com", 
IsNullable = false)]
public __gc class PurchaseOrder
{
public:
   Address* ShipTo;
   String* OrderDate; 
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   [XmlArrayAttribute(S"Items")]
   OrderedItem* OrderedItems[];
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;   
};
 
public __gc class Address
{
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
public:
   [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. */
public:
   [XmlElementAttribute(IsNullable = false)]
   String* City;
   String* State;
   String* Zip;
};
 
public __gc 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 __gc class Test
{
public:
   static void main()
   {
      // Read and write purchase orders.
      Test* t = new Test();
      t->CreatePO(S"po.xml");
      t->ReadPO(S"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 = S"Teresa Atkinson";
      billAddress->Line1 = S"1 Main St.";
      billAddress->City = S"AnyTown";
      billAddress->State = S"WA";
      billAddress->Zip = S"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 = S"Widget S";
      i1->Description = S"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 = Decimal( 0 );
      System::Collections::IEnumerator* myEnum = items->GetEnumerator();
      while (myEnum->MoveNext())
      {
         OrderedItem* oi = __try_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 = 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(this, &Test::serializer_UnknownNode);
      serializer->UnknownAttribute+= new 
      XmlAttributeEventHandler(this, &Test::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 = dynamic_cast<PurchaseOrder*> (serializer->Deserialize(fs));
      // Read the order date.
      Console::WriteLine (S"OrderDate: {0}", po->OrderDate);
  
      // Read the shipping address.
      Address* shipTo = po->ShipTo;
      ReadAddress(shipTo, S"Ship To:");
      // Read the list of ordered items.
      OrderedItem* items[] = po->OrderedItems;
      Console::WriteLine(S"Items to be shipped:");
      System::Collections::IEnumerator* myEnum1 = items->GetEnumerator();
      while (myEnum1->MoveNext())
      {
          OrderedItem* oi = __try_cast<OrderedItem*>(myEnum1->Current);
         Console::WriteLine(S"\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, __box(oi->UnitPrice), __box(oi->Quantity), oi->LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console::WriteLine(S"\t\t\t\t\t Subtotal\t{0}", __box(po->SubTotal));
      Console::WriteLine(S"\t\t\t\t\t Shipping\t{0}", __box(po->ShipCost)); 
      Console::WriteLine(S"\t\t\t\t\t Total\t\t{0}", __box(po->TotalCost));
   }
 
   void ReadAddress(Address* a, String* label)
   {
      // Read the fields of the Address object.
      Console::WriteLine(label);
      Console::WriteLine(S"\t{0}", a->Name );
      Console::WriteLine(S"\t{0}", a->Line1);
      Console::WriteLine(S"\t{0}", a->City);
      Console::WriteLine(S"\t{0}", a->State);
      Console::WriteLine(S"\t{0}", a->Zip );
      Console::WriteLine();
   }

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

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

int main()
{
   Test::main();
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.Xml.Serialization

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

アセンブリ: System.Xml (System.Xml.dll 内)

参照

XmlSerializer メンバ | System.Xml.Serialization 名前空間 | XML シリアル化の概要 | 属性を使用した XML シリアル化の制御 | XML シリアル化の例 | XML スキーマ定義ツールと XML シリアル化 | XmlAttributeOverrides | XmlAttributes