XmlSerializerとは? わかりやすく解説

XmlSerializer イベント


パブリック イベントパブリック イベント

  名前 説明
パブリック イベント UnknownAttribute シリアル化時に XmlSerializer が不明な型の XML 属性認識した場合発生します
パブリック イベント UnknownElement シリアル化時に XmlSerializer不明な型の XML 要素認識した場合発生します
パブリック イベント UnknownNode シリアル化時に XmlSerializer不明な型の XML ノード認識した場合発生します
パブリック イベント UnreferencedObject SOAP エンコード済み XML ストリームの逆シリアル化時にXmlSerializer が、未使用の型または参照されていない型を認識した場合発生します
参照参照

関連項目

XmlSerializer クラス
System.Xml.Serialization 名前空間
XmlAttributeOverrides クラス
XmlAttributes クラス
XmlSerializer クラス
XmlAttributes.XmlText プロパティ
XmlAttributes クラス

その他の技術情報

XML シリアル化概要
方法 : XML ストリーム代替要素名を指定する
属性使用した XML シリアル化制御
XML シリアル化の例
XML スキーマ定義ツール (Xsd.exe)
方法 : 派生クラスシリアル化制御する
<dateTimeSerialization> 要素
<xmlSerializer> 要素

XmlSerializer クラス

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Dim instance As XmlSerializer
public class XmlSerializer
public ref class XmlSerializer
public class XmlSerializer
public class XmlSerializer
解説解説

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

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

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

生成される XML制御

生成されXML制御するために、クラスやそのメンバ特別な属性適用できます。たとえば、異なXML 要素名を指定するには、パブリック フィールドパブリック プロパティに XmlElementAttribute を適用し、ElementName プロパティ設定します類似する属性の完全な一覧については、「XML シリアル化制御する属性」を参照してください。IXmlSerializable インターフェイス実装して、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 ドキュメント内で入れ子にされた要素変換します。たとえば、次のコード最初クラスは、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認識する Boolean フィールド作成し、XmlIgnoreAttribute をそのフィールド適用する方法です。このパターンpropertyNameSpecified形式作成されます。たとえば、"MyFirstName" という名前のフィールドがある場合は、"MyFirstNameSpecified" というフィールド作成して、"MyFirstName" という XML 要素生成するかどうかXmlSerializer指示します。これを次の例に示します

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 つ利点あります第 1 にDLLアクセスしなくても、DLL 内のオブジェクトシリアル化制御および増大できます。第 2 に、シリアル化できるクラス1 セット作成しオブジェクト複数方法シリアル化できます詳細については、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 プロパティから取得します

オブジェクトを逆シリアル化するには、一時ディレクトリ (TEMP 環境変数で定義) に書き込むためのアクセス許可が必要です。

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

パフォーマンス向上するために、XML シリアル化インフラストラクチャでは、指定した型のシリアル化と逆シリアル化を行うアセンブリ動的に生成されます。それらのアセンブリインフラストラクチャによって検索および再利用されます。この動作は、次のコンストラクタ使用するときにだけ発生します

System.Xml.Serialization.XmlSerializer(Type)

System.Xml.Serialization.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;
}
else
{
    // 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
Else 
    ' Use the serializer to serialize, or deserialize.
End If
ArrayList およびジェネリック リストシリアル化

次のようなデータについては、XmlSerializerシリアル化または逆シリアル化することはできません。

使用例使用例

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
        
    Private Sub serializer_UnknownNode(sender
 As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name
 & ControlChars.Tab & e.Text))
    End Sub 'serializer_UnknownNode
    
    
    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 'serializer_UnknownAttribute
End Class 'Test
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 + "'");
   }
}
#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();
}
import System.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import 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. */
/** @attribute 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".
 */
    /** @attribute XmlArrayAttribute("Items")
     */
    public OrderedItem orderedItems[];
    public System.Decimal subTotal;
    public System.Decimal shipCost;
    public System.Decimal totalCost;
} //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). */
    /** @attribute 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.
 */
    /** @attribute XmlElementAttribute(IsNullable = false)
     */
    public String city;
    public String state;
    public String zip;
} //Address

public class OrderedItem
{
    public String itemName;
    public String description;
    public System.Decimal unitPrice;
    public int quantity;
    public System.Decimal lineTotal;

    /* Calculate is a custom method that calculates the price per item,
       and stores the value in a field. */
    public void Calculate()
    {
        lineTotal = Decimal.Multiply(unitPrice, Convert.ToDecimal(quantity));
    } //Calculate
} //OrderedItem

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

    private void CreatePO(String fileName)
    {
        // Create an instance of the XmlSerializer class;
        // specify the type of object to serialize.
        XmlSerializer serializer =
            new XmlSerializer(PurchaseOrder.class.ToType());
        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.get_Now().ToLongDateString();

        // Create an OrderedItem object.
        OrderedItem i1 = new OrderedItem();
        i1.itemName = "Widget S";
        i1.description = "Small widget";
        i1.unitPrice = Convert.ToDecimal(5.23);
        i1.quantity = 3;
        i1.Calculate();

        // Insert the item into the array.
        OrderedItem items[] = { i1 };
        po.orderedItems = items;

        // Calculate the total cost.
        System.Decimal subTotal = new System.Decimal();
        for (int iCtr = 0; iCtr < items.length;
 iCtr++) {
            OrderedItem oi = items[iCtr];
            subTotal = Decimal.Add(subTotal, oi.lineTotal);
        }

        po.subTotal = subTotal;
        po.shipCost = Convert.ToDecimal(12.51);
        po.totalCost = Decimal.Add(po.subTotal, po.shipCost);

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

    protected void ReadPO(String fileName)
    {
        // Create an instance of the XmlSerializer class;
        // specify the type of object to be deserialized.
        XmlSerializer serializer =
            new XmlSerializer(PurchaseOrder.class.ToType());
        /* If the XML document has been altered with unknown 
           nodes or attributes, handle them with the 
           UnknownNode and UnknownAttribute events.*/
        serializer.add_UnknownNode(
            new XmlNodeEventHandler(Serializer_UnknownNode));
        serializer.add_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:");
        for (int iCtr = 0; iCtr < items.length;
 iCtr++) {
            OrderedItem oi = items[iCtr];
            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);
    } //ReadPO

    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();
    } //ReadAddress

    private void Serializer_UnknownNode(Object
 sender, XmlNodeEventArgs e)
    {
        Console.WriteLine("Unknown Node:" + e.get_Name() + "\t"
 + e.get_Text());
    } //Serializer_UnknownNode

    private void Serializer_UnknownAttribute(Object
 sender,
        XmlAttributeEventArgs e)
    {
        System.Xml.XmlAttribute attr = e.get_Attr();
        Console.WriteLine("Unknown attribute " + attr.get_Name() + "='"
            + attr.get_Value() + "'");
    } //Serializer_UnknownAttribute
} //Test
継承階層継承階層
System.Object
  System.Xml.Serialization.XmlSerializer
スレッド セーフスレッド セーフ

この型は、マルチスレッド操作に対して安全です。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlSerializer メンバ
System.Xml.Serialization 名前空間
XmlAttributeOverrides クラス
XmlAttributes クラス
XmlSerializer クラス
XmlAttributes.XmlText プロパティ
XmlAttributes クラス
その他の技術情報
XML シリアル化概要
方法 : XML ストリーム代替要素名を指定する
属性使用した XML シリアル化制御
XML シリアル化の例
XML スキーマ定義ツール (Xsd.exe)
方法 : 派生クラスシリアル化制御する
<dateTimeSerialization> 要素
<xmlSerializer> 要素

XmlSerializer コンストラクタ ()


XmlSerializer コンストラクタ (Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    overrides As XmlAttributeOverrides, _
    extraTypes As Type(), _
    root As XmlRootAttribute, _
    defaultNamespace As String _
)
Dim type As Type
Dim overrides As XmlAttributeOverrides
Dim extraTypes As Type()
Dim root As XmlRootAttribute
Dim defaultNamespace As String

Dim instance As New XmlSerializer(type,
 overrides, extraTypes, root, defaultNamespace)
public XmlSerializer (
    Type type,
    XmlAttributeOverrides overrides,
    Type[] extraTypes,
    XmlRootAttribute root,
    string defaultNamespace
)
public:
XmlSerializer (
    Type^ type, 
    XmlAttributeOverrides^ overrides, 
    array<Type^>^ extraTypes, 
    XmlRootAttribute^ root, 
    String^ defaultNamespace
)
public XmlSerializer (
    Type type, 
    XmlAttributeOverrides overrides, 
    Type[] extraTypes, 
    XmlRootAttribute root, 
    String defaultNamespace
)
public function XmlSerializer (
    type : Type, 
    overrides : XmlAttributeOverrides, 
    extraTypes : Type[], 
    root : XmlRootAttribute, 
    defaultNamespace : String
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

overrides

type パラメータ指定されクラス動作拡張またはオーバーライドする XmlAttributeOverrides。

extraTypes

シリアル化する追加オブジェクト型Type 配列

root

XML ルート要素プロパティ定義する XmlRootAttribute。

defaultNamespace

XML ドキュメント内のすべての XML 要素既定名前空間

解説解説

overrides パラメータにより、基本クラス動作拡張またはオーバーライドするクラスシリアル化する XmlSerializer作成できます。たとえば DLL指定すると、この DLL含まれるクラス継承または拡張するクラス作成できますこのようなクラスシリアル化するには、XmlSerializer構築時に XmlAttributeOverrides クラスインスタンス使用する必要があります詳細については、XmlAttributeOverridesトピック参照してください

既定では、パブリック プロパティまたはパブリック フィールドオブジェクトまたはオブジェクト配列返したときには、それらのオブジェクトの型が自動的にシリアル化されます。ただし、Object 型の配列返すフィールドまたはプロパティクラス含まれている場合は、すべてのオブジェクト配列挿入されます。この場合XmlSerializer に対してObject 配列挿入される可能性のあるすべてのオブジェクトの型を通知しておく必要があります。この場合は、extraTypes パラメータ使用してシリアル化または逆シリアル化する追加オブジェクト型指定する必要があります

XML ドキュメントルート要素には、他のすべての要素入ってます。既定では、type パラメータ指定されオブジェクトルート要素としてシリアル化されますルート要素XML 要素名などのプロパティは、type オブジェクトから取得されます。ただし、root パラメータ使用すると、異な名前空間要素名などを設定するために使用できる XmlRootAttribute オブジェクト指定して既定オブジェクト情報置き換えることができます

defaultName パラメータ使用してXmlSerializer生成するすべての XML 要素既定名前空間指定します

使用例使用例

DLL定義されているクラスインスタンスシリアル化するため、そのクラス内のパブリック メンバオーバーライドする例を次に示します。この例では、追加する型の配列すべての XML 要素既定名前空間、および XML ルート要素情報提供するために使用するクラス指定してます。この例では、先頭部分のコードHighSchool という名前の DLLコンパイル済みであることを前提としています。

'Beginning of the HighSchool.dll 
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports Microsoft.VisualBasic
' Imports HighSchool

Namespace HighSchool

    Public Class Student
        Public Name As String
        Public ID As Integer
    End Class 'Student


    Public Class ClassRoom
        Public Students() As Student
    End Class 'ClassRoom
End Namespace 'HighSchool

Namespace College
    Public Class Graduate
        Inherits HighSchool.Student

        Public Sub New()
        End Sub 'New
        ' Add a new field named University.
        Public University As String
        ' Use extra types to use this field.
        Public Info() As Object
    End Class 'Graduate


    Public Class Address
        Public City As String
    End Class 'Address


    Public Class Phone
        Public Number As String
    End Class 'Phone


    Public Class Run

        Public Shared Sub
 Main()
            Dim test As New
 Run()
            test.WriteOverriddenAttributes("College.xml")
            test.ReadOverriddenAttributes("College.xml")
        End Sub 'Main


        Private Sub WriteOverriddenAttributes(ByVal
 filename As String)
            ' Writing the file requires a TextWriter.
            Dim myStreamWriter As New
 StreamWriter(filename)
            ' Create an XMLAttributeOverrides class.
            Dim attrOverrides As New
 XmlAttributeOverrides()
            ' Create the XmlAttributes class.
            Dim attrs As New
 XmlAttributes()
            ' Override the Student class. "Alumni" is the
 name
            ' of the overriding element in the XML output. 

            Dim attr As New
 XmlElementAttribute("Alumni", GetType(Graduate))
            ' Add the XmlElementAttribute to the collection of
            ' elements in the XmlAttributes object. 
            attrs.XmlElements.Add(attr)
            ' Add the XmlAttributes to the XmlAttributeOverrides.
            ' "Students" is the name being overridden. 
            attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students",
 attrs)

            ' Create array of extra types.
            Dim extraTypes(1) As Type
            extraTypes(0) = GetType(Address)
            extraTypes(1) = GetType(Phone)

            ' Create an XmlRootAttribute.
            Dim root As New
 XmlRootAttribute("Graduates")

            ' Create the XmlSerializer with the
            ' XmlAttributeOverrides object. 
            Dim mySerializer As New
 XmlSerializer(GetType(HighSchool.ClassRoom), _
                attrOverrides, extraTypes, root, "http://www.microsoft.com")

            Dim oMyClass As New
 HighSchool.ClassRoom()

            Dim g1 As New
 Graduate()
            g1.Name = "Jacki"
            g1.ID = 1
            g1.University = "Alma"

            Dim g2 As New
 Graduate()
            g2.Name = "Megan"
            g2.ID = 2
            g2.University = "CM"

            Dim myArray As HighSchool.Student()
 = {g1, g2}

            oMyClass.Students = myArray

            ' Create extra information.
            Dim a1 As New
 Address()
            a1.City = "Ionia"
            Dim a2 As New
 Address()
            a2.City = "Stamford"
            Dim p1 As New
 Phone()
            p1.Number = "555-0101"
            Dim p2 As New
 Phone()
            p2.Number = "555-0100"

            Dim o1() As Object
 = {a1, p1}
            Dim o2() As Object
 = {a2, p2}

            g1.Info = o1
            g2.Info = o2
            mySerializer.Serialize(myStreamWriter, oMyClass)
            myStreamWriter.Close()
        End Sub 'WriteOverriddenAttributes


        Private Sub ReadOverriddenAttributes(ByVal
 filename As String)
            ' The majority of the code here is the same as that in the
            ' WriteOverriddenAttributes method. Because the XML being
 read
            ' doesn't conform to the schema defined by the DLL, the
            ' XMLAttributesOverrides must be used to create an
            ' XmlSerializer instance to read the XML document.

            Dim attrOverrides As New
 XmlAttributeOverrides()
            Dim attrs As New
 XmlAttributes()
            Dim attr As New
 XmlElementAttribute("Alumni", GetType(Graduate))
            attrs.XmlElements.Add(attr)
            attrOverrides.Add(GetType(HighSchool.ClassRoom), "Students",
 attrs)

            Dim extraTypes(1) As Type
            extraTypes(0) = GetType(Address)
            extraTypes(1) = GetType(Phone)

            Dim root As New
 XmlRootAttribute("Graduates")

            Dim readSerializer As New
 XmlSerializer(GetType(HighSchool.ClassRoom), _
                attrOverrides, extraTypes, root, "http://www.microsoft.com")

            ' A FileStream object is required to read the file. 
            Dim fs As New
 FileStream(filename, FileMode.Open)

            Dim oMyClass As HighSchool.ClassRoom
            oMyClass = CType(readSerializer.Deserialize(fs), HighSchool.ClassRoom)

            ' Here is the difference between reading and writing an
            ' XML document: You must declare an object of the derived
            ' type (Graduate) and cast the Student instance to it.
            Dim g As Graduate
            Dim a As Address
            Dim p As Phone
            Dim grad As Graduate
            For Each grad In
 oMyClass.Students
                g = CType(grad, Graduate)
                Console.Write((g.Name & ControlChars.Tab))
                Console.Write((g.ID & ControlChars.Tab))
                Console.Write((g.University & ControlChars.Cr))
                a = CType(g.Info(0), Address)
                Console.WriteLine(a.City)
                p = CType(g.Info(1), Phone)
                Console.WriteLine(p.Number)
            Next grad
        End Sub 'ReadOverriddenAttributes
    End Class 'Run
End Namespace 'College
// Beginning of the HighSchool.dll 

namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }
    
   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization; 
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
       // Use extra types to use this field.
       public object[]Info;
    }
 
    public class Address
    {
       public string City;
    }
 
    public class Phone
    {
       public string Number;
    }
    
   public class Run
   {
      public static void
 Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }
 
      private void WriteOverriddenAttributes(string
 filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();
         /* Override the Student class. "Alumni" is
 the name
         of the overriding element in the XML output. */

         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);
         /* Add the XmlAttributes to the XmlAttributeOverrides. 
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);
 
         // Create array of extra types.
         Type [] extraTypes = new Type[2];
         extraTypes[0]=typeof(Address);
         extraTypes[1]=typeof(Phone);
 
         // Create an XmlRootAttribute.
         XmlRootAttribute root = new XmlRootAttribute("Graduates");
          
         /* Create the XmlSerializer with the 
         XmlAttributeOverrides object. */
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");
 
         MyClass myClass= new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jacki";
         g1.ID = 1;
         g1.University = "Alma";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};

         myClass.Students = myArray;
 
         // Create extra information.
         Address a1 = new Address();
         a1.City = "Ionia";
         Address a2 = new Address();
         a2.City = "Stamford";
         Phone p1 = new Phone();
         p1.Number = "555-0101";
         Phone p2 = new Phone();
         p2.Number = "555-0100";
 
         Object[]o1 = new Object[2]{a1, p1};
         Object[]o2 = new Object[2]{a2,p2};
 
         g1.Info = o1;
         g2.Info = o2;
         mySerializer.Serialize(myStreamWriter,myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string
 filename)
      {
         /* The majority of the code here is the same as that in
 the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an 
         XmlSerializer instance to read the XML document.*/
          
         XmlAttributeOverrides attrOverrides = new 
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);

         Type [] extraTypes = new Type[2];
         extraTypes[0] = typeof(Address);
         extraTypes[1] = typeof(Phone);
 
         XmlRootAttribute root = new XmlRootAttribute("Graduates");
          
         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");

         // A FileStream object is required to read the file. 
         FileStream fs = new FileStream(filename, FileMode.Open);
          
         MyClass myClass;
         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an 
         XML document: You must declare an object of the derived 
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;
         Address a;
         Phone p;
         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
            a = (Address) g.Info[0];
            Console.WriteLine(a.City);
            p = (Phone) g.Info[1];
            Console.WriteLine(p.Number);
         }
      }
   }
}
// Beginning of the HighSchool.dll 
#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Serialization;

namespace HighSchool
{
   public ref class Student
   {
   public:
      String^ Name;
      int ID;
   };

   public ref class MyClass
   {
   public:
      array<Student^>^Students;
   };
}

namespace College
{

using namespace HighSchool;
   public ref class Graduate: public
 HighSchool::Student
   {
   public:
      Graduate(){}

      // Add a new field named University.
      String^ University;

      // Use extra types to use this field.
      array<Object^>^Info;
   };

   public ref class Address
   {
   public:
      String^ City;
   };

   public ref class Phone
   {
   public:
      String^ Number;
   };

   public ref class Run
   {
   public:
      static void main()
      {
         Run^ test = gcnew Run;
         test->WriteOverriddenAttributes( "College.xml" );
         test->ReadOverriddenAttributes( "College.xml" );
      }

   private:
      void WriteOverriddenAttributes( String^ filename )
      {
         // Writing the file requires a TextWriter.
         TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

         // Create the XmlAttributes class.
         XmlAttributes^ attrs = gcnew XmlAttributes;

         /* Override the Student class. "Alumni" is
 the name
               of the overriding element in the XML output. */
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid
 );

         /* Add the XmlElementAttribute to the collection of
               elements in the XmlAttributes object. */
         attrs->XmlElements->Add( attr );

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
               "Students" is the name being overridden. */
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students",
 attrs );

         // Create array of extra types.
         array<Type^>^extraTypes = gcnew array<Type^>(2);
         extraTypes[ 0 ] = Address::typeid;
         extraTypes[ 1 ] = Phone::typeid;

         // Create an XmlRootAttribute.
         XmlRootAttribute^ root = gcnew XmlRootAttribute( "Graduates" );

         /* Create the XmlSerializer with the 
               XmlAttributeOverrides object. */
         XmlSerializer^ mySerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides,extraTypes,root,"http://www.microsoft.com"
 );
         MyClass ^ myClass = gcnew MyClass;
         Graduate^ g1 = gcnew Graduate;
         g1->Name = "Jacki";
         g1->ID = 1;
         g1->University = "Alma";
         Graduate^ g2 = gcnew Graduate;
         g2->Name = "Megan";
         g2->ID = 2;
         g2->University = "CM";
         array<Student^>^myArray = {g1,g2};
         myClass->Students = myArray;

         // Create extra information.
         Address^ a1 = gcnew Address;
         a1->City = "Ionia";
         Address^ a2 = gcnew Address;
         a2->City = "Stamford";
         Phone^ p1 = gcnew Phone;
         p1->Number = "555-0101";
         Phone^ p2 = gcnew Phone;
         p2->Number = "555-0100";
         array<Object^>^o1 = {a1,p1};
         array<Object^>^o2 = {a2,p2};
         g1->Info = o1;
         g2->Info = o2;
         mySerializer->Serialize( myStreamWriter, myClass );
         myStreamWriter->Close();
      }

      void ReadOverriddenAttributes( String^ filename )
      {
         /* The majority of the code here is the same as that in
 the
               WriteOverriddenAttributes method. Because the XML being read
               doesn't conform to the schema defined by the DLL, the
               XMLAttributesOverrides must be used to create an 
               XmlSerializer instance to read the XML document.*/
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
         XmlAttributes^ attrs = gcnew XmlAttributes;
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid
 );
         attrs->XmlElements->Add( attr );
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students",
 attrs );
         array<Type^>^extraTypes = gcnew array<Type^>(2);
         extraTypes[ 0 ] = Address::typeid;
         extraTypes[ 1 ] = Phone::typeid;
         XmlRootAttribute^ root = gcnew XmlRootAttribute( "Graduates" );
         XmlSerializer^ readSerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides,extraTypes,root,"http://www.microsoft.com"
 );

         // A FileStream object is required to read the file. 
         FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
         MyClass ^ myClass;
         myClass = dynamic_cast<MyClass^>(readSerializer->Deserialize( fs
 ));
         
         /* Here is the difference between reading and writing an 
               XML document: You must declare an object of the derived 
               type (Graduate) and cast the Student instance to it.*/
         Graduate^ g;
         Address^ a;
         Phone^ p;
         System::Collections::IEnumerator^ myEnum = myClass->Students->GetEnumerator();
         while ( myEnum->MoveNext() )
         {
            Graduate^ grad = safe_cast<Graduate^>(myEnum->Current);
            g = dynamic_cast<Graduate^>(grad);
            Console::Write( "{0}\t", g->Name );
            Console::Write( "{0}\t", g->ID );
            Console::Write( "{0}\n", g->University );
            a = dynamic_cast<Address^>(g->Info[ 0 ]);
            Console::WriteLine( a->City );
            p = dynamic_cast<Phone^>(g->Info[ 1 ]);
            Console::WriteLine( p->Number );
         }
      }
   };
}

int main()
{
   College::Run::main();
}
package College;

import System.*;
import System.IO.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import HighSchool.*;
public class Graduate extends HighSchool.Student
{
    public Graduate()
    {
    } //Graduate
    // Add a new field named University.
    public String university;
    // Use extra types to use this field.
    public Object info[];
} //Graduate

public class Address
{
    public String city;
} //Address

public class Phone
{
    public String number;
} //Phone

public class Run
{
    public static void main(String[]
 args)
    {
        Run test = new Run();
        test.WriteOverriddenAttributes("College.xml");
        test.ReadOverriddenAttributes("College.xml");
    } //main

    private void WriteOverriddenAttributes(String
 filename)
    {
        // Writing the file requires a TextWriter.
        TextWriter myStreamWriter = new StreamWriter(filename);

        // Create an XMLAttributeOverrides class.
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

        // Create the XmlAttributes class.
        XmlAttributes attrs = new XmlAttributes();

        /* Override the Student class. "Alumni" is the
 name
           of the overriding element in the XML output. */
        XmlElementAttribute attr =
            new XmlElementAttribute("Alumni", Graduate.class.ToType());

        /* Add the XmlElementAttribute to the collection of
           elements in the XmlAttributes object. */
        attrs.get_XmlElements().Add(attr);

        /* Add the XmlAttributes to the XmlAttributeOverrides. 
          "Students" is the name being overridden. */
        attrOverrides.Add(HighSchool.MyClass.class.ToType(), "students",
 attrs);

        // Create array of extra types.
        Type extraTypes[] = new Type[2];
        extraTypes.set_Item(0, Address.class.ToType());
        extraTypes.set_Item(1, Phone.class.ToType());

        // Create an XmlRootAttribute.
        XmlRootAttribute root = new XmlRootAttribute("Graduates");

        /* Create the XmlSerializer with the 
           XmlAttributeOverrides object. */
        XmlSerializer mySerializer =
            new XmlSerializer(HighSchool.MyClass.class.ToType(),
 attrOverrides,
            extraTypes, root, "http://www.microsoft.com");
        MyClass myClass = new MyClass();
        
        Graduate g1 = new Graduate();
        g1.name = "Jacki";
        g1.iD = 1;
        g1.university = "Alma";

        Graduate g2 = new Graduate();
        g2.name = "Megan";
        g2.iD = 2;
        g2.university = "CM";

        Student myArray[] =  { g1, g2 };
        myClass.students = myArray;

        // Create extra information.
        Address a1 = new Address();
        a1.city = "Ionia";

        Address a2 = new Address();
        a2.city = "Stamford";

        Phone p1 = new Phone();
        p1.number = "000-0000";

        Phone p2 = new Phone();
        p2.number = "555-0100";

        Object o1[] = new Object[] { a1, p1 };
        Object o2[] = new Object[] { a2, p2 };

        g1.info = o1;
        g2.info = o2;
        mySerializer.Serialize(myStreamWriter, myClass);
        myStreamWriter.Close();
    } //WriteOverriddenAttributes

    private void ReadOverriddenAttributes(String
 filename)
    {
        /* The majority of the code here is the same as that in
 the
           WriteOverriddenAttributes method. Because the XML being read
           doesn't conform to the schema defined by the DLL, the
           XMLAttributesOverrides must be used to create an 
           XmlSerializer instance to read the XML document.*/
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();
        XmlElementAttribute attr =
            new XmlElementAttribute("Alumni", Graduate.class.ToType());

        attrs.get_XmlElements().Add(attr);
        attrOverrides.Add(HighSchool.MyClass.class.ToType(), "students",
 attrs);

        Type extraTypes[] = new Type[2];
        extraTypes.set_Item(0, Address.class.ToType());
        extraTypes.set_Item(1, Phone.class.ToType());

        XmlRootAttribute root = new XmlRootAttribute("Graduates");
        XmlSerializer readSerializer =
            new XmlSerializer(HighSchool.MyClass.class.ToType(),
 attrOverrides,
            extraTypes, root, "http://www.microsoft.com");

        // A FileStream object is required to read the file. 
        FileStream fs = new FileStream(filename, FileMode.Open);
        MyClass myClass;
        myClass = (MyClass)readSerializer.Deserialize(fs);

        /* Here is the difference between reading and writing an 
           XML document: You must declare an object of the derived 
           type (Graduate) and cast the Student instance to it.*/
        Graduate g;
        Address a;
        Phone p;

        for (int iCtr = 0; iCtr < myClass.students.length;
 iCtr++) {
            Graduate grad = (Graduate)myClass.students[iCtr];
            g = (Graduate)grad;
            Console.Write(g.name + "\t");
            Console.Write(g.iD + "\t");
            Console.Write(g.university + "\n");
            a = (Address)g.info[0];
            Console.WriteLine(a.city);
            p = (Phone)g.info[1];
            Console.WriteLine(p.number);
        }
    } //ReadOverriddenAttributes
} //Run
package HighSchool;
// Beginning of the HighSchool.dll 
public class Student
{
    public String name;
    public int iD;
} //Student

public class MyClass
{
    public Student students[];
} //MyClass
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (Type)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

public XmlSerializer (
    Type type
)
public:
XmlSerializer (
    Type^ type
)
public XmlSerializer (
    Type type
)
public function XmlSerializer (
    type : Type
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

解説解説
使用例使用例

Widget という名前のシンプルなオブジェクトシリアル化する XmlSerializer構築例を次に示します。この例では、オブジェクト各種プロパティ設定してから Serialize メソッド呼び出します。

Private Sub SerializeObject(ByVal
 filename As String)
    Dim serializer As New
 XmlSerializer(GetType(OrderedItem))
    
    ' Create an instance of the class to be serialized.
    Dim i As New OrderedItem()
    
    ' Set the public property values.
    With i
        .ItemName = "Widget"
        .Description = "Regular Widget"
        .Quantity = 10
        .UnitPrice = CDec(2.3)
    End With
    
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    
    ' Serialize the object, and close the TextWriter.
    serializer.Serialize(writer, i)
    writer.Close()
End Sub


' This is the class that will be serialized.
Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
End Class

private void SerializeObject(string
 filename)
{
   XmlSerializer serializer = 
   new XmlSerializer(typeof(OrderedItem));

   // Create an instance of the class to be serialized.
   OrderedItem i = new OrderedItem();

   // Set the public property values.
   i.ItemName = "Widget";
   i.Description = "Regular Widget";
   i.Quantity = 10;
   i.UnitPrice = (decimal) 2.30;

   // Writing the document requires a TextWriter.
   TextWriter writer = new StreamWriter(filename);

   // Serialize the object, and close the TextWriter.
   serializer.Serialize(writer, i);
   writer.Close();
}

// This is the class that will be serialized.
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
}

private:
   void SerializeObject( String^ filename )
   {
      XmlSerializer^ serializer =
         gcnew XmlSerializer( OrderedItem::typeid );

      // Create an instance of the class to be serialized.
      OrderedItem^ i = gcnew OrderedItem;

      // Set the public property values.
      i->ItemName = "Widget";
      i->Description = "Regular Widget";
      i->Quantity = 10;
      i->UnitPrice = (Decimal)2.30;

      // Writing the document requires a TextWriter.
      TextWriter^ writer = gcnew StreamWriter( filename );

      // Serialize the object, and close the TextWriter.
      serializer->Serialize( writer, i );
      writer->Close();
   }

public:
   // This is the class that will be serialized.
   ref class OrderedItem
   {
   public:
      String^ ItemName;
      String^ Description;
      Decimal UnitPrice;
      int Quantity;
   };
private void SerializeObject(String filename)
{
    XmlSerializer serializer =
        new XmlSerializer(OrderedItem.class.ToType());

    // Create an instance of the class to be serialized.
    OrderedItem i = new OrderedItem();

    // Set the public property values.
    i.itemName = "Widget";
    i.description = "Regular Widget";
    i.quantity = 10;
    i.unitPrice = Convert.ToDecimal(2.3);

    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);

    // Serialize the object, and close the TextWriter.
    serializer.Serialize(writer, i);
    writer.Close();
} //SerializeObject

// This is the class that will be serialized.
public class OrderedItem
{
    public String itemName;
    public String description;
    public System.Decimal unitPrice;
    public int quantity;
} //OrderedItem
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (XmlTypeMapping)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    xmlTypeMapping As XmlTypeMapping _
)
Dim xmlTypeMapping As XmlTypeMapping

Dim instance As New XmlSerializer(xmlTypeMapping)
public XmlSerializer (
    XmlTypeMapping xmlTypeMapping
)
public:
XmlSerializer (
    XmlTypeMapping^ xmlTypeMapping
)
public XmlSerializer (
    XmlTypeMapping xmlTypeMapping
)
public function XmlSerializer (
    xmlTypeMapping : XmlTypeMapping
)

パラメータ

xmlTypeMapping

1 つの型から別の型への割り当てを行う XmlTypeMapping。

解説解説

このコンストラクタは、オブジェクトSOAP メッセージシリアル化するときに XmlSerializer作成するために使用します生成される SOAP メッセージ制御するには、System.Xml.Serialization 名前空間内にある (名前が "Soap" で始まる) 特別な属性使用します

使用例使用例

Group というクラスシリアル化する例を次に示しますGroupName フィールドIgnoreThis フィールド、および GroupType 列挙体のメンバシリアル化オーバーライドされますCreateOverrideSerializer メソッド内では、SoapAttributeOverrides オブジェクト作成されオーバーライド対象メンバまたは列挙体ごとに、適切なプロパティ設定された SoapAttributes オブジェクト作成されそれぞれSoapAttributeOverrides オブジェクト追加されています。XmlMapping オブジェクトSoapAttributeOverrides オブジェクト使用して作成され、その XmlMapping使用して既定シリアル化オーバーライドする XmlSerializer作成されます。

Imports System
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.Schema

Public Class Group
   <SoapAttribute (Namespace:= "http:'www.cpandl.com")>
 _
   Public GroupName As String
 
   
   <SoapAttribute(DataType:= "base64Binary")>
 _
   Public GroupNumber() As Byte

   <SoapAttribute(DataType:= "date", _
   AttributeName:= "CreationDate")> _
   Public Today As DateTime 
   <SoapElement(DataType:= "nonNegativeInteger",
 _
   ElementName:= "PosInt")> _
   Public PostitiveInt As String
 
   ' This is ignored when serialized unless it's overridden.
   <SoapIgnore> _ 
   Public IgnoreThis As Boolean
 
   
   Public Grouptype As GroupType 

   Public MyVehicle As Vehicle 

   '  The SoapInclude allows the method to return a Car.
   <SoapInclude(GetType(Car))> _
   Public Function myCar(licNumber As
 String ) As Vehicle 
      Dim v As Vehicle 
      if licNumber = "" Then
         v = New Car()
         v.licenseNumber = "!!!!!!"
      else  
          v = New Car()
          v.licenseNumber = licNumber
      End If
      
      return v
   End Function
End Class
  
' SoapInclude allows Vehicle to accept Car type.
<SoapInclude(GetType(Car))> _
Public MustInherit  class
 Vehicle
   Public licenseNumber As String
 
   Public makeDate As DateTime 
End Class

Public Class Car
   Inherits Vehicle

End Class

Public enum GroupType
   ' These enums can be overridden.
   <SoapEnum("Small")> _
   A
   <SoapEnum("Large")> _ 
   B
End Enum
 
Public Class Run

   Shared Sub Main()
      Dim test As Run = New
 Run()
      test.SerializeOriginal("SoapOriginal.xml")
      test.SerializeOverride("SoapOverrides.xml")
      test.DeserializeOriginal("SoapOriginal.xml")
      test.DeserializeOverride("SoapOverrides.xml")
   End SUb
   
   Public Sub SerializeOriginal(filename As
 String)

      ' Create an instance of the XmlSerializer class.
      Dim myMapping As XmlTypeMapping = _
      (New SoapReflectionImporter().ImportTypeMapping _
      (GetType(Group)))
      Dim mySerializer As XmlSerializer = 
 _
      New XmlSerializer(myMapping)
      
      Dim myGroup As Group =MakeGroup()
      ' Writing the file requires a TextWriter.
      Dim writer As XmlTextWriter  = _
      New XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ' Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup)
      writer.WriteEndElement()
      writer.Close()
   End Sub

   Public Sub SerializeOverride(filename As
 String)
      ' Create an instance of the XmlSerializer class
      ' that overrides the serialization.
      Dim overRideSerializer As XmlSerializer
 = _
      CreateOverrideSerializer()
      Dim myGroup As Group =MakeGroup()
      ' Writing the file requires a TextWriter.
      Dim writer As XmlTextWriter  = _
      New XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ' Serialize the class, and close the TextWriter.
      overRideSerializer.Serialize(writer, myGroup)
      writer.WriteEndElement()
      writer.Close()
    End Sub

   private Function MakeGroup() As
 Group 
      ' Create an instance of the class that will be serialized.
      Dim myGroup As Group  = New
 Group()

      ' Set the object properties.
      myGroup.GroupName = ".NET"

      Dim hexByte()As Byte = new
 Byte(1){Convert.ToByte(100), _
      Convert.ToByte(50)}
      myGroup.GroupNumber = hexByte

      Dim myDate As DateTime  = new
 DateTime(2002,5,2)
      myGroup.Today = myDate

      myGroup.PostitiveInt = "10000"
    myGroup.IgnoreThis = true
    myGroup.Grouptype = GroupType.B
    Dim thisCar As Car 
    thisCar =CType(myGroup.myCar("1234566"), Car)
    myGroup.myVehicle=thisCar
      return myGroup
   End Function       

   Public Sub DeserializeOriginal(filename
 As String)
      ' Create an instance of the XmlSerializer class.
      Dim myMapping As XmlTypeMapping = _
      (New SoapReflectionImporter().ImportTypeMapping _
      (GetType(Group)))
      Dim mySerializer As XmlSerializer = 
 _
      New XmlSerializer(myMapping)

      ' Reading the file requires an  XmlTextReader.
      Dim reader As XmlTextReader = _
      New XmlTextReader(filename)
      reader.ReadStartElement("wrapper")

      ' Deserialize and cast the object.
      Dim myGroup As Group  = _
      CType(mySerializer.Deserialize(reader), Group)
      reader.ReadEndElement()
      reader.Close()
   End Sub

   Public Sub DeserializeOverride(filename
 As String)
      ' Create an instance of the XmlSerializer class.
      Dim overRideSerializer As XmlSerializer
  = _
      CreateOverrideSerializer()

      ' Reading the file requires an  XmlTextReader.
      Dim reader As XmlTextReader = _
      New XmlTextReader(filename)
      reader.ReadStartElement("wrapper")

      ' Deserialize and cast the object.
      Dim myGroup As Group = _
      CType(overRideSerializer.Deserialize(reader), Group)
      reader.ReadEndElement()
      reader.Close()
      ReadGroup(myGroup)
   End Sub

   private Sub ReadGroup(myGroup As
 Group)
      Console.WriteLine(myGroup.GroupName)
      Console.WriteLine(myGroup.GroupNumber(0))
      Console.WriteLine(myGroup.GroupNumber(1))
      Console.WriteLine(myGroup.Today)
      Console.WriteLine(myGroup.PostitiveInt)
      Console.WriteLine(myGroup.IgnoreThis)
      Console.WriteLine()
   End Sub
   
   Private Function CreateOverrideSerializer()
 As XmlSerializer
      Dim soapOver As SoapAttributeOverrides
 = New SoapAttributeOverrides()
      Dim soapAtts As SoapAttributes = New
 SoapAttributes()

      Dim mySoapElement As SoapElementAttribute
 = New SoapElementAttribute()
      mySoapElement.ElementName = "xxxx"
      soapAtts.SoapElement = mySoapElement
      soapOver.Add(GetType(Group), "PostitiveInt",
 soapAtts)

      ' Override the IgnoreThis property.
      Dim myIgnore As SoapIgnoreAttribute 
 = new SoapIgnoreAttribute()
      soapAtts = New SoapAttributes()
      soapAtts.SoapIgnore = false
      soapOver.Add(GetType(Group), "IgnoreThis",
 soapAtts)

      ' Override the GroupType enumeration.
      soapAtts = New SoapAttributes()
      Dim xSoapEnum As SoapEnumAttribute =
 new SoapEnumAttribute()
      xSoapEnum.Name = "Over1000"
      soapAtts.SoapEnum = xSoapEnum
      ' Add the SoapAttributes to the SoapOverrides object.
      soapOver.Add(GetType(GroupType), "A",
 soapAtts)

      ' Create second enumeration and add it.
      soapAtts = New SoapAttributes()
      xSoapEnum = New SoapEnumAttribute()
      xSoapEnum.Name = "ZeroTo1000"
      soapAtts.SoapEnum = xSoapEnum
      soapOver.Add(GetType(GroupType), "B",
 soapAtts)

      ' Override the Group type.
      soapAtts = New SoapAttributes()
      Dim soapType As SoapTypeAttribute = New
 SoapTypeAttribute()
      soapType.TypeName = "Team"
      soapAtts.SoapType = soapType
      soapOver.Add(GetType(Group),soapAtts)
    
      Dim myMapping As XmlTypeMapping = (New
 SoapReflectionImporter( _
      soapOver)).ImportTypeMapping(GetType(Group))
    
       Dim ser As XmlSerializer = new
 XmlSerializer(myMapping)
      return ser
   End Function
End Class
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;

public class Group
{
   [SoapAttribute (Namespace = "http://www.cpandl.com")]
   public string GroupName;
   
   [SoapAttribute(DataType = "base64Binary")]
   public Byte [] GroupNumber;

   [SoapAttribute(DataType = "date", AttributeName = "CreationDate")]
   public DateTime Today;
   [SoapElement(DataType = "nonNegativeInteger", ElementName = "PosInt")]
   public string PostitiveInt;
   // This is ignored when serialized unless it's overridden.
   [SoapIgnore] 
   public bool IgnoreThis;
   
   public GroupType Grouptype;

   public Vehicle MyVehicle;

   // The SoapInclude allows the method to return a Car.
   [SoapInclude(typeof(Car))]
   public Vehicle myCar(string licNumber)
   {
      Vehicle v;
      if(licNumber == "")
         {
            v = new Car();
           v.licenseNumber = "!!!!!!";
        }
      else
        {
          v = new Car();
          v.licenseNumber = licNumber;
        }
      return v;
   }
}
  
// SoapInclude allows Vehicle to accept Car type.
[SoapInclude(typeof(Car))]
public abstract class Vehicle
{
   public string licenseNumber;
   public DateTime makeDate;
}

public class Car: Vehicle
{
}

public enum GroupType
{
   // These enums can be overridden.
   [SoapEnum("Small")]
   A,
   [SoapEnum("Large")]
   B
}
 
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeOriginal("SoapOriginal.xml");
      test.SerializeOverride("SoapOverrides.xml");
      test.DeserializeOriginal("SoapOriginal.xml");
      test.DeserializeOverride("SoapOverrides.xml");
   
   }
   public void SerializeOriginal(string
 filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping = 
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =  
      new XmlSerializer(myMapping);
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();
   }

   public void SerializeOverride(string
 filename)
   {
      // Create an instance of the XmlSerializer class
      // that overrides the serialization.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      overRideSerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();

   }

   private Group MakeGroup(){
      // Create an instance of the class that will be serialized.
      Group myGroup = new Group();

      // Set the object properties.
      myGroup.GroupName = ".NET";

      Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
      Convert.ToByte(50)};
      myGroup.GroupNumber = hexByte;

      DateTime myDate = new DateTime(2002,5,2);
      myGroup.Today = myDate;
      myGroup.PostitiveInt= "10000";
      myGroup.IgnoreThis=true;
      myGroup.Grouptype= GroupType.B;
      Car thisCar =(Car)  myGroup.myCar("1234566");
      myGroup.MyVehicle=thisCar;
      return myGroup;
   }       

   public void DeserializeOriginal(string
 filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping = 
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =  
      new XmlSerializer(myMapping);


      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader= 
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup; 
      myGroup = (Group) mySerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();

   }

   public void DeserializeOverride(string
 filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();

      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader= 
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup; 
      myGroup = (Group) overRideSerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();
      ReadGroup(myGroup);
   }

   private void ReadGroup(Group myGroup){
      Console.WriteLine(myGroup.GroupName);
      Console.WriteLine(myGroup.GroupNumber[0]);
      Console.WriteLine(myGroup.GroupNumber[1]);
      Console.WriteLine(myGroup.Today);
      Console.WriteLine(myGroup.PostitiveInt);
      Console.WriteLine(myGroup.IgnoreThis);
      Console.WriteLine();
   }
   private XmlSerializer CreateOverrideSerializer()
   {
      SoapAttributeOverrides mySoapAttributeOverrides = 
      new SoapAttributeOverrides();
      SoapAttributes soapAtts = new SoapAttributes();

      SoapElementAttribute mySoapElement = new SoapElementAttribute();
      mySoapElement.ElementName = "xxxx";
      soapAtts.SoapElement = mySoapElement;
      mySoapAttributeOverrides.Add(typeof(Group), "PostitiveInt", 
      soapAtts);

      // Override the IgnoreThis property.
      SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
      soapAtts = new SoapAttributes();
      soapAtts.SoapIgnore = false;      
      mySoapAttributeOverrides.Add(typeof(Group), "IgnoreThis", 
      soapAtts);

      // Override the GroupType enumeration.    
      soapAtts = new SoapAttributes();
      SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "Over1000";
      soapAtts.SoapEnum = xSoapEnum;

      // Add the SoapAttributes to the 
      // mySoapAttributeOverridesrides object.
      mySoapAttributeOverrides.Add(typeof(GroupType), "A", 
      soapAtts);

      // Create second enumeration and add it.
      soapAtts = new SoapAttributes();
      xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "ZeroTo1000";
      soapAtts.SoapEnum = xSoapEnum;
      mySoapAttributeOverrides.Add(typeof(GroupType), "B", 
      soapAtts);

      // Override the Group type.
      soapAtts = new SoapAttributes();
      SoapTypeAttribute soapType = new SoapTypeAttribute();
      soapType.TypeName = "Team";
      soapAtts.SoapType = soapType;
      mySoapAttributeOverrides.Add(typeof(Group),soapAtts);

      // Create an XmlTypeMapping that is used to create an instance
 
      // of the XmlSerializer. Then return the XmlSerializer object.
      XmlTypeMapping myMapping = (new SoapReflectionImporter(
      mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));
    
      XmlSerializer ser = new XmlSerializer(myMapping);
      return ser;
   }
}
import System.*;
import System.IO.*;
import System.Text.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import System.Xml.Schema.*;

public class Group
{
    /** @attribute SoapAttribute(Namespace = "http://www.cpandl.com")
     */
    public String groupName;

    /** @attribute SoapAttribute(DataType = "base64Binary")
     */
    public System.Byte groupNumber[];

    /** @attribute SoapAttribute(DataType = "date", 
        AttributeName = "CreationDate")
     */
    public DateTime today;

    /** @attribute SoapElement(DataType = "nonNegativeInteger", 
        ElementName = "PosInt")
     */
    public String postitiveInt;

    // This is ignored when serialized unless it's overridden.
    /** @attribute SoapIgnore()
     */
    public boolean ignoreThis;
    public GroupType groupType;
    public Vehicle myVehicle;

    // The SoapInclude allows the method to return a Car.
    /** @attribute SoapInclude(Car.class)
     */
    public Vehicle MyCar(String licNumber)
    {
        Vehicle v;
        if (licNumber.Equals("")) {
            v = new Car();
            v.licenseNumber = "!!!!!!";
        }
        else {
            v = new Car();
            v.licenseNumber = licNumber;
        }
        return v;
    } //MyCar
} //Group

// SoapInclude allows Vehicle to accept Car type.
/** @attribute SoapInclude(Car.class)
 */
abstract public class Vehicle
{
    public String licenseNumber;
    public DateTime makeDate;
} //Vehicle

public class Car extends Vehicle
{
} //Car

public class GroupType
{
    public int member;

    public GroupType()
    {
        member = 0;
    } //GroupType

    public GroupType(int n)
    {
        member = n;
    } //GroupType

    /** @attribute SoapEnum("Small")
     */
    public static int a
 = 0;

    /** @attribute SoapEnum("Large")
     */
    public static int b
 = 1;
} //GroupType

public class Run
{
    public static void main(String[]
 args)
    {
        Run test = new Run();
        test.SerializeOriginal("SoapOriginal.xml");
        test.SerializeOverride("SoapOverrides.xml");
        test.DeserializeOriginal("SoapOriginal.xml");
        test.DeserializeOverride("SoapOverrides.xml");
    } //main

    public void SerializeOriginal(String fileName)
    {
        // Create an instance of the XmlSerializer class.
        XmlTypeMapping myMapping = (new SoapReflectionImporter()).
            ImportTypeMapping(Group.class.ToType());
        XmlSerializer mySerializer = new XmlSerializer(myMapping);
        Group myGroup = MakeGroup();
        // Writing the file requires a TextWriter.
        XmlTextWriter writer = new XmlTextWriter(fileName, 
            Encoding.get_UTF8());
        writer.set_Formatting(Formatting.Indented);
        writer.WriteStartElement("wrapper");
        // Serialize the class, and close the TextWriter.
        mySerializer.Serialize(writer, myGroup);
        writer.WriteEndElement();
        writer.Close();
    } //SerializeOriginal

    public void SerializeOverride(String fileName)
    {
        // Create an instance of the XmlSerializer class
        // that overrides the serialization.
        XmlSerializer overRideSerializer = CreateOverrideSerializer();
        Group myGroup = MakeGroup();
        // Writing the file requires a TextWriter.
        XmlTextWriter writer = new XmlTextWriter(fileName, 
            Encoding.get_UTF8());
        writer.set_Formatting(Formatting.Indented);
        writer.WriteStartElement("wrapper");
        // Serialize the class, and close the TextWriter.
        overRideSerializer.Serialize(writer, myGroup);
        writer.WriteEndElement();
        writer.Close();
    } //SerializeOverride

    private Group MakeGroup()
    {
        // Create an instance of the class that will be serialized.
        Group myGroup = new Group();
        // Set the object properties.
        myGroup.groupName = ".NET";

        System.Byte hexByte[] = new System.Byte[] { (System.Byte)100,
 
            (System.Byte)50 };
        myGroup.groupNumber = hexByte;

        DateTime myDate = new DateTime(2002, 5, 2);
        myGroup.today = myDate;
        myGroup.postitiveInt = "10000";
        myGroup.ignoreThis = true;
        myGroup.groupType = new GroupType(GroupType.b);
        Car thisCar = (Car)myGroup.MyCar("1234566");
        myGroup.myVehicle = thisCar;
        return myGroup;
    } //MakeGroup

    public void DeserializeOriginal(String
 fileName)
    {
        // Create an instance of the XmlSerializer class.
        XmlTypeMapping myMapping = (new SoapReflectionImporter()).
            ImportTypeMapping(Group.class.ToType());
        XmlSerializer mySerializer = new XmlSerializer(myMapping);
        // Reading the file requires an  XmlTextReader.
        XmlTextReader reader = new XmlTextReader(fileName);
        reader.ReadStartElement("wrapper");
        // Deserialize and cast the object.
        Group myGroup;
        myGroup = (Group)mySerializer.Deserialize(reader);
        reader.ReadEndElement();
        reader.Close();
    } //DeserializeOriginal

    public void DeserializeOverride(String
 fileName)
    {
        // Create an instance of the XmlSerializer class.
        XmlSerializer overRideSerializer = CreateOverrideSerializer();
        // Reading the file requires an  XmlTextReader.
        XmlTextReader reader = new XmlTextReader(fileName);
        reader.ReadStartElement("wrapper");
        // Deserialize and cast the object.
        Group myGroup;
        myGroup = (Group)overRideSerializer.Deserialize(reader);
        reader.ReadEndElement();
        reader.Close();
        ReadGroup(myGroup);
    } //DeserializeOverride

    private void ReadGroup(Group myGroup)
    {
        Console.WriteLine(myGroup.groupName);
        Console.WriteLine(myGroup.groupNumber.get_Item(0));
        Console.WriteLine(myGroup.groupNumber.get_Item(1));
        Console.WriteLine(myGroup.today);
        Console.WriteLine(myGroup.postitiveInt);
        Console.WriteLine(myGroup.ignoreThis);
        Console.WriteLine();
    } //ReadGroup

    private XmlSerializer CreateOverrideSerializer()
    {
        SoapAttributeOverrides mySoapAttributeOverrides 
            = new SoapAttributeOverrides();
        SoapAttributes soapAtts = new SoapAttributes();

        SoapElementAttribute mySoapElement = new SoapElementAttribute();
        mySoapElement.set_ElementName("xxxx");
        soapAtts.set_SoapElement(mySoapElement);
        mySoapAttributeOverrides.Add(Group.class.ToType(), "postitiveInt",
 
            soapAtts);
        // Override the ignoreThis property.
        SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
        soapAtts = new SoapAttributes();
        soapAtts.set_SoapIgnore(false);
        mySoapAttributeOverrides.Add(Group.class.ToType(), "ignoreThis",
 
            soapAtts);
        // Override the GroupType enumeration.    
        soapAtts = new SoapAttributes();
        SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
        xSoapEnum.set_Name("Over1000");
        soapAtts.set_SoapEnum(xSoapEnum);
        // Add the SoapAttributes to the 
        // mySoapAttributeOverridesrides object.
        mySoapAttributeOverrides.Add(GroupType.class.ToType(),
 "a", soapAtts);
        // Create second enumeration and add it.
        soapAtts = new SoapAttributes();
        xSoapEnum = new SoapEnumAttribute();
        xSoapEnum.set_Name("ZeroTo1000");
        soapAtts.set_SoapEnum(xSoapEnum);
        mySoapAttributeOverrides.Add(GroupType.class.ToType(),
 "b", soapAtts);
        // Override the Group type.
        soapAtts = new SoapAttributes();
        SoapTypeAttribute soapType = new SoapTypeAttribute();
        soapType.set_TypeName("Team");
        soapAtts.set_SoapType(soapType);
        mySoapAttributeOverrides.Add(Group.class.ToType(), soapAtts);
        // Create an XmlTypeMapping that is used to create an instance
 
        // of the XmlSerializer. Then return the XmlSerializer object.
        XmlTypeMapping myMapping = new SoapReflectionImporter(
            mySoapAttributeOverrides).ImportTypeMapping(Group.class.ToType());

        XmlSerializer ser = new XmlSerializer(myMapping);
        return ser;
    } //CreateOverrideSerializer
} //Run
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (Type, XmlAttributeOverrides)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    overrides As XmlAttributeOverrides _
)
Dim type As Type
Dim overrides As XmlAttributeOverrides

Dim instance As New XmlSerializer(type,
 overrides)
public XmlSerializer (
    Type type,
    XmlAttributeOverrides overrides
)
public:
XmlSerializer (
    Type^ type, 
    XmlAttributeOverrides^ overrides
)
public XmlSerializer (
    Type type, 
    XmlAttributeOverrides overrides
)
public function XmlSerializer (
    type : Type, 
    overrides : XmlAttributeOverrides
)

パラメータ

type

シリアル化するオブジェクトの型。

overrides

XmlAttributeOverrides。

解説解説
使用例使用例

DLL定義されているクラスインスタンスシリアル化するため、DLL 内のパブリック メンバオーバーライドする例を次に示します

' Beginning of HighSchool.dll
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports Microsoft.VisualBasic
Imports HighSchool

Namespace HighSchool
    
    Public Class Student
        Public Name As String
        Public ID As Integer
    End Class 'Student
    
    
    Public Class MyClass1
        Public Students() As Student
    End Class 'MyClass1
End Namespace 'HighSchool

Namespace College
    Public Class Graduate
        Inherits HighSchool.Student
        
        Public Sub New()
        End Sub 'New ' Add a new
 field named University.
        Public University As String
    End Class 'Graduate
    
    
    
    Public Class Run
        
        Public Shared Sub
 Main()
            Dim test As New
 Run()
            test.WriteOverriddenAttributes("College.xml")
            test.ReadOverriddenAttributes("College.xml")
        End Sub 'Main
        
        
        Private Sub WriteOverriddenAttributes(filename
 As String)
            ' Writing the file requires a TextWriter.
            Dim myStreamWriter As New
 StreamWriter(filename)
            ' Create an XMLAttributeOverrides class.
            Dim attrOverrides As New
 XmlAttributeOverrides()
            ' Create the XmlAttributes class.
            Dim attrs As New
 XmlAttributes()
            
            ' Override the Student class. "Alumni" is the
 name
            ' of the overriding element in the XML output. 
            Dim attr As New
 XmlElementAttribute("Alumni", GetType(Graduate))
            
            ' Add the XmlElementAttribute to the collection of
            ' elements in the XmlAttributes object. 
            attrs.XmlElements.Add(attr)
            
            ' Add the XmlAttributes to the XmlAttributeOverrides. 
            ' "Students" is the name being overridden. 
            attrOverrides.Add(GetType(HighSchool.MyClass1), "Students",
 attrs)
            
            ' Create the XmlSerializer. 
            Dim mySerializer As New
 XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
            
            Dim oMyClass As New
 MyClass1()
            
            Dim g1 As New
 Graduate()
            g1.Name = "Jackie"
            g1.ID = 1
            g1.University = "Alma Mater"
            
            Dim g2 As New
 Graduate()
            g2.Name = "Megan"
            g2.ID = 2
            g2.University = "CM"
            
            Dim myArray As Student() =  {g1,
 g2}
            oMyClass.Students = myArray
            
            mySerializer.Serialize(myStreamWriter, oMyClass)
            myStreamWriter.Close()
        End Sub 'WriteOverriddenAttributes
        
        
        Private Sub ReadOverriddenAttributes(filename
 As String)
            ' The majority of the code here is the same as that in the
            ' WriteOverriddenAttributes method. Because the XML being
 read
            ' doesn't conform to the schema defined by the DLL, the
            ' XMLAttributesOverrides must be used to create an
            ' XmlSerializer instance to read the XML document.
            
            Dim attrOverrides As New
 XmlAttributeOverrides()
            Dim attrs As New
 XmlAttributes()
            Dim attr As New
 XmlElementAttribute("Alumni", GetType(Graduate))
            attrs.XmlElements.Add(attr)
            attrOverrides.Add(GetType(HighSchool.MyClass1), "Students",
 attrs)
            
            Dim readSerializer As New
 XmlSerializer(GetType(HighSchool.MyClass1), attrOverrides)
            
            ' To read the file, a FileStream object is required. 
            Dim fs As New
 FileStream(filename, FileMode.Open)
            
            Dim oMyClass As MyClass1
            
            oMyClass = CType(readSerializer.Deserialize(fs), MyClass1)
            
            ' Here is the difference between reading and writing an
            ' XML document: You must declare an object of the derived
            ' type (Graduate) and cast the Student instance to it.
            Dim g As Graduate
            
            Dim grad As Graduate
            For Each grad In
  oMyClass.Students
                g = CType(grad, Graduate)
                Console.Write((g.Name & ControlChars.Tab))
                Console.Write((g.ID.ToString & ControlChars.Tab))
                Console.Write((g.University & ControlChars.Cr))
            Next grad
        End Sub 'ReadOverriddenAttributes
    End Class 'Run
End Namespace 'College
// Beginning of HighSchool.dll
namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }
    
   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization; 
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
    }
 
    
   public class Run
   {
      public static void
 Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }
 
      private void WriteOverriddenAttributes(string
 filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides = 
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();

         /* Override the Student class. "Alumni" is
 the name
         of the overriding element in the XML output. */
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));

         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);
          
         // Create the XmlSerializer. 
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);
 
         MyClass myClass = new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jackie";
         g1.ID = 1;
         g1.University = "Alma Mater";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};
         myClass.Students = myArray;
 
         mySerializer.Serialize(myStreamWriter, myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string
 filename)
      {
         /* The majority of the code here is the same as that in
 the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an 
         XmlSerializer instance to read the XML document.*/
          
         XmlAttributeOverrides attrOverrides = new 
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr = 
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass), 
         "Students", attrs);

         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);

         // To read the file, a FileStream object is required. 
         FileStream fs = new FileStream(filename, FileMode.Open);
          
         MyClass myClass;

         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an 
         XML document: You must declare an object of the derived 
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;

         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
         }
      }
   }
}
// Beginning of HighSchool.dll
#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Serialization;

namespace HighSchool
{
   public ref class Student
   {
   public:
      String^ Name;
      int ID;
   };

   public ref class MyClass
   {
   public:
      array<Student^>^Students;
   };
}

namespace College
{

using namespace HighSchool;
   public ref class Graduate: public
 HighSchool::Student
   {
   public:
      Graduate(){}

      // Add a new field named University.
      String^ University;
   };

   public ref class Run
   {
   public:
      static void main()
      {
         Run^ test = gcnew Run;
         test->WriteOverriddenAttributes( "College.xml" );
         test->ReadOverriddenAttributes( "College.xml" );
      }

   private:
      void WriteOverriddenAttributes( String^ filename )
      {
         // Writing the file requires a TextWriter.
         TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

         // Create the XmlAttributes class.
         XmlAttributes^ attrs = gcnew XmlAttributes;

         /* Override the Student class. "Alumni" is
 the name
               of the overriding element in the XML output. */
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid
 );

         /* Add the XmlElementAttribute to the collection of
               elements in the XmlAttributes object. */
         attrs->XmlElements->Add( attr );

         /* Add the XmlAttributes to the XmlAttributeOverrides. 
               "Students" is the name being overridden. */
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students",
 attrs );

         // Create the XmlSerializer. 
         XmlSerializer^ mySerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides
 );
         MyClass ^ myClass = gcnew MyClass;
         Graduate^ g1 = gcnew Graduate;
         g1->Name = "Jackie";
         g1->ID = 1;
         g1->University = "Alma Mater";
         Graduate^ g2 = gcnew Graduate;
         g2->Name = "Megan";
         g2->ID = 2;
         g2->University = "CM";
         array<Student^>^myArray = {g1,g2};
         myClass->Students = myArray;
         mySerializer->Serialize( myStreamWriter, myClass );
         myStreamWriter->Close();
      }

      void ReadOverriddenAttributes( String^ filename )
      {
         /* The majority of the code here is the same as that in
 the
               WriteOverriddenAttributes method. Because the XML being read
               doesn't conform to the schema defined by the DLL, the
               XMLAttributesOverrides must be used to create an 
               XmlSerializer instance to read the XML document.*/
         XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
         XmlAttributes^ attrs = gcnew XmlAttributes;
         XmlElementAttribute^ attr = gcnew XmlElementAttribute( "Alumni",Graduate::typeid
 );
         attrs->XmlElements->Add( attr );
         attrOverrides->Add( HighSchool::MyClass::typeid, "Students",
 attrs );
         XmlSerializer^ readSerializer = gcnew XmlSerializer( HighSchool::MyClass::typeid,attrOverrides
 );
         
         // To read the file, a FileStream object is required. 
         FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
         MyClass ^ myClass;
         myClass = dynamic_cast<MyClass^>(readSerializer->Deserialize( fs
 ));

         /* Here is the difference between reading and writing an 
               XML document: You must declare an object of the derived 
               type (Graduate) and cast the Student instance to it.*/
         Graduate^ g;
         System::Collections::IEnumerator^ myEnum = myClass->Students->GetEnumerator();
         while ( myEnum->MoveNext() )
         {
            Graduate^ grad = safe_cast<Graduate^>(myEnum->Current);
            g = dynamic_cast<Graduate^>(grad);
            Console::Write( "{0}\t", g->Name );
            Console::Write( "{0}\t", g->ID );
            Console::Write( "{0}\n", g->University );
         }
      }
   };
}

int main()
{
   College::Run::main();
}
package College;

import System.*;
import System.IO.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import HighSchool.*;

public class Graduate extends HighSchool.Student
{
    public Graduate()
    {        
    } //Graduate
    // Add a new field named University.
    public String university;
} //Graduate

public class Run
{
    public static void main(String[]
 args)
    {
        Run test = new Run();
        test.WriteOverriddenAttributes("College.xml");
        test.ReadOverriddenAttributes("College.xml");
    } //main

    private void WriteOverriddenAttributes(String
 filename)
    {
        // Writing the file requires a TextWriter.
        TextWriter myStreamWriter = new StreamWriter(filename);

        // Create an XMLAttributeOverrides class.
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

        // Create the XmlAttributes class.
        XmlAttributes attrs = new XmlAttributes();

        /* Override the Student class. "Alumni" is the
 name
           of the overriding element in the XML output. */
        XmlElementAttribute attr =
            new XmlElementAttribute("Alumni", Graduate.class.ToType());

        /* Add the XmlElementAttribute to the collection of
           elements in the XmlAttributes object. */
        attrs.get_XmlElements().Add(attr);

        /* Add the XmlAttributes to the XmlAttributeOverrides. 
           "Students" is the name being overridden. */
        attrOverrides.Add(HighSchool.MyClass.class.ToType(), "students",
 attrs);

        // Create the XmlSerializer. 
        XmlSerializer mySerializer =
            new XmlSerializer(HighSchool.MyClass.class.ToType(),
 attrOverrides);
        MyClass myClass = new MyClass();

        Graduate g1 = new Graduate();
        g1.name = "Jackie";
        g1.iD = 1;
        g1.university = "Alma Mater";

        Graduate g2 = new Graduate();
        g2.name = "Megan";
        g2.iD = 2;
        g2.university = "CM";

        Student myArray[] =  { g1, g2 };
        myClass.students = myArray;

        mySerializer.Serialize(myStreamWriter, myClass);
        myStreamWriter.Close();
    } //WriteOverriddenAttributes

    private void ReadOverriddenAttributes(String
 filename)
    {
        /* The majority of the code here is the same as that in
 the
           WriteOverriddenAttributes method. Because the XML being read
           doesn't conform to the schema defined by the DLL, the
           XMLAttributesOverrides must be used to create an 
           XmlSerializer instance to read the XML document.*/
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();
        XmlElementAttribute attr =
            new XmlElementAttribute("Alumni", Graduate.class.ToType());
        attrs.get_XmlElements().Add(attr);
        attrOverrides.Add(HighSchool.MyClass.class.ToType(), "students",
 attrs);

        XmlSerializer readSerializer =
            new XmlSerializer(HighSchool.MyClass.class.ToType(),
 attrOverrides);

        // To read the file, a FileStream object is required. 
        FileStream fs = new FileStream(filename, FileMode.Open);
        MyClass myClass;
        myClass = (MyClass)readSerializer.Deserialize(fs);

        /* Here is the difference between reading and writing an 
           XML document: You must declare an object of the derived 
           type (Graduate) and cast the Student instance to it.*/
        Graduate g;
        for (int iCtr = 0; iCtr < myClass.students.length;
 iCtr++) {
            Graduate grad = (Graduate)myClass.students[iCtr];
            g = (Graduate)grad;
            Console.Write(g.name + "\t");
            Console.Write(g.iD + "\t");
            Console.Write(g.university + "\n");
        }
    } //ReadOverriddenAttributes
} //Run
package HighSchool;
// Beginning of HighSchool.dll
public class Student
{
    public String name;
    public int iD;
} //Student

public class MyClass
{
    public Student students[];
} //MyClass
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (Type, Type[])

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    extraTypes As Type() _
)
Dim type As Type
Dim extraTypes As Type()

Dim instance As New XmlSerializer(type,
 extraTypes)
public XmlSerializer (
    Type type,
    Type[] extraTypes
)
public:
XmlSerializer (
    Type^ type, 
    array<Type^>^ extraTypes
)
public XmlSerializer (
    Type type, 
    Type[] extraTypes
)
public function XmlSerializer (
    type : Type, 
    extraTypes : Type[]
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

extraTypes

シリアル化する追加オブジェクト型Type 配列

解説解説
使用例使用例

オブジェクト配列返すパブリック フィールドを含むクラスインスタンスシリアル化する例を次に示しますXmlSerializer コンストラクタextraTypes パラメータは、シリアル化して配列挿入できるオブジェクトの型を指定します

Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization



' This defines the object that will be serialized.
Public Class Teacher
    Public Name As String
    
    Public Sub New()
    End Sub 'New 
    ' Note that the Info field returns an array of objects.
    ' Any object can be added to the array by adding the
    ' object type to the array passed to the extraTypes argument. 
    <XmlArray(ElementName := "ExtraInfo", IsNullable
 := True)> _
    Public Info() As Object
    Public PhoneInfo As Phone
End Class 'Teacher


' This defines one of the extra types to be included.
Public Class Address
    Public City As String
    
    Public Sub New()
    End Sub 'New
    
    Public Sub New(city
 As String)
        me.City = city
    End Sub 'New
End Class 'Address
 

' Another extra type to include.
Public Class Phone
    Public PhoneNumber As String
    
    Public Sub New()
    End Sub 'New
    
    Public Sub New(phoneNumber
 As String)
        me.PhoneNumber = phoneNumber
    End Sub 'New
End Class 'Phone


' Another type, derived from Phone.
Public Class InternationalPhone
    Inherits Phone
    Public CountryCode As String
    
    
    Public Sub New()
    End Sub 'New
     
    Public Sub New(countryCode
 As String)
        me.CountryCode = countryCode
    End Sub 'New
End Class 'InternationalPhone


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New
 Run()
        test.SerializeObject("Teacher.xml")
        test.DeserializeObject("Teacher.xml")
    End Sub 'Main
    
    
    Private Sub SerializeObject(filename As
 String)
        ' Writing the file requires a TextWriter.
        Dim myStreamWriter As New
 StreamWriter(filename)
        
        ' Create a Type array.
        Dim extraTypes(2) As Type
        extraTypes(0) = GetType(Address)
        extraTypes(1) = GetType(Phone)
        extraTypes(2) = GetType(InternationalPhone)
        
        ' Create the XmlSerializer instance.
        Dim mySerializer As New
 XmlSerializer(GetType(Teacher), extraTypes)
        
        Dim teacher As New
 Teacher()
        teacher.Name = "Mike"
        ' Add extra types to the Teacher object.
        Dim info(1) As Object
        info(0) = New Address("Springville")
        info(1) = New Phone("555-0100")
        
        teacher.Info = info
        
        teacher.PhoneInfo = New InternationalPhone("000")
        
        mySerializer.Serialize(myStreamWriter, teacher)
        myStreamWriter.Close()
    End Sub 'SerializeObject
    
    
    Private Sub DeserializeObject(filename
 As String)
        ' Create a Type array.
        Dim extraTypes(2) As Type
        extraTypes(0) = GetType(Address)
        extraTypes(1) = GetType(Phone)
        extraTypes(2) = GetType(InternationalPhone)
        
        ' Create the XmlSerializer instance.
        Dim mySerializer As New
 XmlSerializer(GetType(Teacher), extraTypes)
        
        ' Reading a file requires a FileStream.
        Dim fs As New FileStream(filename,
 FileMode.Open)
        Dim teacher As Teacher = CType(mySerializer.Deserialize(fs),
 Teacher)
        
        ' Read the extra information.
        Dim a As Address = CType(teacher.Info(0),
 Address)
        Dim p As Phone = CType(teacher.Info(1),
 Phone)
        Dim Ip As InternationalPhone = CType(teacher.PhoneInfo,
 InternationalPhone)
        
        Console.WriteLine(teacher.Name)
        Console.WriteLine(a.City)
        Console.WriteLine(p.PhoneNumber)
        Console.WriteLine(Ip.CountryCode)
    End Sub 'DeserializeObject
End Class 'Run
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// This defines the object that will be serialized.
public class Teacher
{  
   public string Name;
   public Teacher(){}
   /* Note that the Info field returns an array of objects.
      Any object can be added to the array by adding the
      object type to the array passed to the extraTypes argument. */
   [XmlArray (ElementName = "ExtraInfo", IsNullable = true)]
   public object[] Info;
   public Phone PhoneInfo;
}
 
// This defines one of the extra types to be included.
public class Address
{  
   public string City;

   public Address(){}
   public Address(string city)
   {
      City = city;
   }

}

// Another extra type to include.
public class Phone
{
   public string PhoneNumber;
   public Phone(){}
   public Phone(string phoneNumber)
   {
      PhoneNumber = phoneNumber;
   }
}

// Another type, derived from Phone
public class InternationalPhone:Phone
{
   public string CountryCode;

   public InternationalPhone(){}

   public InternationalPhone(string countryCode)
   {
      CountryCode = countryCode;
   }
}
    
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("Teacher.xml");
      test.DeserializeObject("Teacher.xml");
   }
 
   private void SerializeObject(string
 filename)
   {
      // Writing the file requires a TextWriter.
      TextWriter myStreamWriter = new StreamWriter(filename);
 
      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);
          
      Teacher teacher = new Teacher();
      teacher.Name = "Mike";
      // Add extra types to the Teacher object
      object [] info = new object[2];
      info[0] = new Address("Springville");
      info[1] = new Phone("555-0100");
         
      teacher.Info = info;

      teacher.PhoneInfo = new InternationalPhone("000");
 

      mySerializer.Serialize(myStreamWriter,teacher);
      myStreamWriter.Close();
   }
 
   private void DeserializeObject(string
 filename)
   {
      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);
      
      // Reading a file requires a FileStream.
      FileStream fs = new FileStream(filename, FileMode.Open);
      Teacher teacher = (Teacher) mySerializer.Deserialize(fs);
         
      // Read the extra information.
      Address a = (Address)teacher.Info[0];
      Phone p = (Phone) teacher.Info[1];
      InternationalPhone Ip = 
      (InternationalPhone) teacher.PhoneInfo;

      Console.WriteLine(teacher.Name);
      Console.WriteLine(a.City);
      Console.WriteLine(p.PhoneNumber);
      Console.WriteLine(Ip.CountryCode);
   }
}
#using <System.Xml.dll>
#using <System.dll>

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

// This defines the object that will be serialized.
public ref class Teacher
{
public:
   String^ Name;
   Teacher(){}

   /* Note that the Info field returns an array of objects.
         Any object can be added to the array by adding the
         object type to the array passed to the extraTypes argument. */

   [XmlArray(ElementName="ExtraInfo",IsNullable=true)]
   array<Object^>^Info;
   Phone^ PhoneInfo;
};


// This defines one of the extra types to be included.
public ref class Address
{
public:
   String^ City;
   Address(){}

   Address( String^ city )
   {
      City = city;
   }
};

// Another extra type to include.
public ref class Phone
{
public:
   String^ PhoneNumber;
   Phone(){}

   Phone( String^ phoneNumber )
   {
      PhoneNumber = phoneNumber;
   }
};

// Another type, derived from Phone
public ref class InternationalPhone: public
 Phone
{
public:
   String^ CountryCode;
   InternationalPhone(){}

   InternationalPhone( String^ countryCode )
   {
      CountryCode = countryCode;
   }
};

public ref class Run
{
public:
   static void main()
   {
      Run^ test = gcnew Run;
      test->SerializeObject( "Teacher.xml" );
      test->DeserializeObject( "Teacher.xml" );
   }

private:
   void SerializeObject( String^ filename )
   {
      // Writing the file requires a TextWriter.
      TextWriter^ myStreamWriter = gcnew StreamWriter( filename );

      // Create a Type array.
      array<Type^>^extraTypes = gcnew array<Type^>(3);
      extraTypes[ 0 ] = Address::typeid;
      extraTypes[ 1 ] = Phone::typeid;
      extraTypes[ 2 ] = InternationalPhone::typeid;

      // Create the XmlSerializer instance.
      XmlSerializer^ mySerializer = gcnew XmlSerializer( Teacher::typeid,extraTypes
 );
      Teacher^ teacher = gcnew Teacher;
      teacher->Name = "Mike";

      // Add extra types to the Teacher object
      array<Object^>^info = gcnew array<Object^>(2);
      info[ 0 ] = gcnew Address( "Springville" );
      info[ 1 ] = gcnew Phone( "555-0100" );
      teacher->Info = info;
      teacher->PhoneInfo = gcnew InternationalPhone( "000" );
      mySerializer->Serialize( myStreamWriter, teacher );
      myStreamWriter->Close();
   }

   void DeserializeObject( String^ filename )
   {
      // Create a Type array.
      array<Type^>^extraTypes = gcnew array<Type^>(3);
      extraTypes[ 0 ] = Address::typeid;
      extraTypes[ 1 ] = Phone::typeid;
      extraTypes[ 2 ] = InternationalPhone::typeid;

      // Create the XmlSerializer instance.
      XmlSerializer^ mySerializer = gcnew XmlSerializer( Teacher::typeid,extraTypes
 );

      // Reading a file requires a FileStream.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
      Teacher^ teacher = dynamic_cast<Teacher^>(mySerializer->Deserialize(
 fs ));

      // Read the extra information.
      Address^ a = dynamic_cast<Address^>(teacher->Info[ 0 ]);
      Phone^ p = dynamic_cast<Phone^>(teacher->Info[ 1 ]);
      InternationalPhone^ Ip = dynamic_cast<InternationalPhone^>(teacher->PhoneInfo);
      Console::WriteLine( teacher->Name );
      Console::WriteLine( a->City );
      Console::WriteLine( p->PhoneNumber );
      Console::WriteLine( Ip->CountryCode );
   }
};

int main()
{
   Run::main();
}
import System.*;
import System.IO.*;
import System.Xml.*;
import System.Xml.Serialization.*;

// This defines the object that will be serialized.
public class Teacher
{
    public String name;

    public Teacher()
    {
    } //Teacher
    /* Note that the Info field returns an array of objects.
       Any object can be added to the array by adding the
       object type to the array passed to the extraTypes argument. */
    /** @attribute XmlArray(ElementName = "ExtraInfo", IsNullable = true)
     */
    public Object info[];
    public Phone phoneInfo;
} //Teacher

// This defines one of the extra types to be included.
public class Address
{
    public String city;
    public Address()
    {
    } //Address
    public Address(String tCity)
    {
        city = tCity;
    } //Address
} //Address 

// Another extra type to include.
public class Phone
{
    public String phoneNumber;
    public Phone()
    {
    } //Phone
    public Phone(String tPhoneNumber)
    {
        phoneNumber = tPhoneNumber;
    } //Phone
} //Phone

// Another type, derived from Phone
public class InternationalPhone extends Phone
{
    public String countryCode;
    public InternationalPhone()
    {
    } //InternationalPhone
    public InternationalPhone(String tCountryCode)
    {
        countryCode = tCountryCode;
    } //InternationalPhone
} //InternationalPhone

public class Run
{
    public static void main(String[]
 args)
    {
        Run test = new Run();
        test.SerializeObject("Teacher.xml");
        test.DeserializeObject("Teacher.xml");
    } //main

    private void SerializeObject(String filename)
    {
        // Writing the file requires a TextWriter.
        TextWriter myStreamWriter = new StreamWriter(filename);

        // Create a Type array.
        Type extraTypes[] = new Type[3];

        extraTypes.set_Item(0, Address.class.ToType());
        extraTypes.set_Item(1, Phone.class.ToType());
        extraTypes.set_Item(2, InternationalPhone.class.ToType());

        // Create the XmlSerializer instance.
        XmlSerializer mySerializer =
            new XmlSerializer(Teacher.class.ToType(),
 extraTypes);
        Teacher teacher = new Teacher();

        teacher.name = "Mike";

        // Add extra types to the Teacher object
        Object info[] = new Object[2];

        info.set_Item(0, new Address("Springville"));
        info.set_Item(1, new Phone("000-0000"));
        teacher.info = info;
        teacher.phoneInfo = new InternationalPhone("000");
        mySerializer.Serialize(myStreamWriter, teacher);
        myStreamWriter.Close();
    } //SerializeObject


    private void DeserializeObject(String filename)
    {
        // Create a Type array.
        Type extraTypes[] = new Type[3];

        extraTypes.set_Item(0, Address.class.ToType());
        extraTypes.set_Item(1, Phone.class.ToType());
        extraTypes.set_Item(2, InternationalPhone.class.ToType());

        // Create the XmlSerializer instance.
        XmlSerializer mySerializer =
            new XmlSerializer(Teacher.class.ToType(),
 extraTypes);

        // Reading a file requires a FileStream.
        FileStream fs = new FileStream(filename, FileMode.Open);
        Teacher teacher = (Teacher)mySerializer.Deserialize(fs);

        // Read the extra information.
        Address a = (Address)teacher.info[0];
        Phone p = (Phone)teacher.info[1];
        InternationalPhone ip = (InternationalPhone)teacher.phoneInfo;

        Console.WriteLine(teacher.name);
        Console.WriteLine(a.city);
        Console.WriteLine(p.phoneNumber);
        Console.WriteLine(ip.countryCode);
    } //DeserializeObject
} //Run
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (Type, XmlRootAttribute)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    root As XmlRootAttribute _
)
Dim type As Type
Dim root As XmlRootAttribute

Dim instance As New XmlSerializer(type,
 root)
public XmlSerializer (
    Type type,
    XmlRootAttribute root
)
public:
XmlSerializer (
    Type^ type, 
    XmlRootAttribute^ root
)
public XmlSerializer (
    Type type, 
    XmlRootAttribute root
)
public function XmlSerializer (
    type : Type, 
    root : XmlRootAttribute
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

root

XML ルート要素を表す XmlRootAttribute。

解説解説
使用例使用例

名前空間要素名などの XML ルート要素各種プロパティを含む XmlRootAttribute使用する XmlSerializer構築例を次に示します

Private Sub SerializeObject(ByVal
 filename As String)
    ' Create an XmlRootAttribute, and set its properties.
    Dim xRoot As New XmlRootAttribute()
    xRoot.ElementName = "CustomRoot"
    xRoot.Namespace = "http://www.cpandl.com"
    xRoot.IsNullable = True
    
    ' Construct the XmlSerializer with the XmlRootAttribute.
    Dim serializer As New
 XmlSerializer(GetType(OrderedItem), xRoot)
    
    ' Create an instance of the object to serialize.
    Dim i As New OrderedItem()
    ' Insert code to set properties of the ordered item.
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    
    serializer.Serialize(writer, i)
    writer.Close()
End Sub
    
Private Sub DeserializeObject(ByVal
 filename As String)
    ' Create an XmlRootAttribute, and set its properties.
    Dim xRoot As New XmlRootAttribute()
    xRoot.ElementName = "CustomRoot"
    xRoot.Namespace = "http://www.cpandl.com"
    xRoot.IsNullable = True
    
    Dim serializer As New
 XmlSerializer(GetType(OrderedItem), xRoot)
    
    ' A FileStream is needed to read the XML document.
    Dim fs As New FileStream(filename,
 FileMode.Open)
    ' Deserialize the object.
    Dim i As OrderedItem = CType(serializer.Deserialize(fs),
 OrderedItem)
    ' Insert code to use the object's properties and methods.
End Sub
     
private void SerializeObject(string
 filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;
     
    // Construct the XmlSerializer with the XmlRootAttribute.
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);
     
    // Create an instance of the object to serialize.
    OrderedItem i = new OrderedItem();
    // Insert code to set properties of the ordered item.
     
    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);
     
    serializer.Serialize(writer, i);
    writer.Close();
}

private void DeserializeObject(string
 filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;
     
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);
     
    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);
    // Deserialize the object.
    OrderedItem i = (OrderedItem) serializer.Deserialize(fs);
    // Insert code to use the object's properties and methods.
}

private:
   void SerializeObject( String^ filename )
   {
      // Create an XmlRootAttribute, and set its properties.
      XmlRootAttribute^ xRoot = gcnew XmlRootAttribute;
      xRoot->ElementName = "CustomRoot";
      xRoot->Namespace = "http://www.cpandl.com";
      xRoot->IsNullable = true;

      // Construct the XmlSerializer with the XmlRootAttribute.
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,xRoot );

      // Create an instance of the object to serialize.
      OrderedItem^ i = gcnew OrderedItem;
      // Insert code to set properties of the ordered item.

      // Writing the document requires a TextWriter.
      TextWriter^ writer = gcnew StreamWriter( filename );
      serializer->Serialize( writer, i );
      writer->Close();
   }

   void DeserializeObject( String^ filename )
   {
      // Create an XmlRootAttribute, and set its properties.
      XmlRootAttribute^ xRoot = gcnew XmlRootAttribute;
      xRoot->ElementName = "CustomRoot";
      xRoot->Namespace = "http://www.cpandl.com";
      xRoot->IsNullable = true;

      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,xRoot );

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
      // Deserialize the object.
      OrderedItem^ i = dynamic_cast<OrderedItem^>(serializer->Deserialize(
 fs ));
      // Insert code to use the object's properties and methods.
   }
private void SerializeObject(String filename)
{
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.set_ElementName("CustomRoot");
    xRoot.set_Namespace("http://www.cpandl.com");
    xRoot.set_IsNullable(true);

    // Construct the XmlSerializer with the XmlRootAttribute.
    XmlSerializer serializer =
        new XmlSerializer(OrderedItem.class.ToType(),
 xRoot);

    // Create an instance of the object to serialize.
    OrderedItem i = new OrderedItem();

    // Insert code to set properties of the ordered item.
    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);
    serializer.Serialize(writer, i);
    writer.Close();
} //SerializeObject

private void DeserializeObject(String filename)
{
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.set_ElementName("CustomRoot");
    xRoot.set_Namespace("http://www.cpandl.com");
    xRoot.set_IsNullable(true);

    XmlSerializer serializer =
        new XmlSerializer(OrderedItem.class.ToType(),
 xRoot);

    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);

    // Deserialize the object.
    OrderedItem i = (OrderedItem)serializer.Deserialize(fs);
    // Insert code to use the object's properties and methods.
} //DeserializeObject
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ (Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    overrides As XmlAttributeOverrides, _
    extraTypes As Type(), _
    root As XmlRootAttribute, _
    defaultNamespace As String, _
    location As String, _
    evidence As Evidence _
)
Dim type As Type
Dim overrides As XmlAttributeOverrides
Dim extraTypes As Type()
Dim root As XmlRootAttribute
Dim defaultNamespace As String
Dim location As String
Dim evidence As Evidence

Dim instance As New XmlSerializer(type,
 overrides, extraTypes, root, defaultNamespace, location, evidence)
public XmlSerializer (
    Type type,
    XmlAttributeOverrides overrides,
    Type[] extraTypes,
    XmlRootAttribute root,
    string defaultNamespace,
    string location,
    Evidence evidence
)
public:
XmlSerializer (
    Type^ type, 
    XmlAttributeOverrides^ overrides, 
    array<Type^>^ extraTypes, 
    XmlRootAttribute^ root, 
    String^ defaultNamespace, 
    String^ location, 
    Evidence^ evidence
)
public XmlSerializer (
    Type type, 
    XmlAttributeOverrides overrides, 
    Type[] extraTypes, 
    XmlRootAttribute root, 
    String defaultNamespace, 
    String location, 
    Evidence evidence
)
public function XmlSerializer (
    type : Type, 
    overrides : XmlAttributeOverrides, 
    extraTypes : Type[], 
    root : XmlRootAttribute, 
    defaultNamespace : String, 
    location : String, 
    evidence : Evidence
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

overrides

type パラメータ指定されクラス動作拡張またはオーバーライドする XmlAttributeOverrides。

extraTypes

シリアル化する追加オブジェクト型Type 配列

root

XML ルート要素プロパティ定義する XmlRootAttribute。

defaultNamespace

XML ドキュメント内のすべての XML 要素既定名前空間

location

型の位置

evidence

型にアクセスするために必要な資格情報を含む Evidence クラスインスタンス

解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlSerializer クラス
XmlSerializer メンバ
System.Xml.Serialization 名前空間

XmlSerializer コンストラクタ (Type, String)

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

名前空間: System.Xml.Serialization
アセンブリ: System.Xml (system.xml.dll 内)
構文構文

Public Sub New ( _
    type As Type, _
    defaultNamespace As String _
)
Dim type As Type
Dim defaultNamespace As String

Dim instance As New XmlSerializer(type,
 defaultNamespace)
public XmlSerializer (
    Type type,
    string defaultNamespace
)
public:
XmlSerializer (
    Type^ type, 
    String^ defaultNamespace
)
public XmlSerializer (
    Type type, 
    String defaultNamespace
)
public function XmlSerializer (
    type : Type, 
    defaultNamespace : String
)

パラメータ

type

XmlSerializer がシリアル化できるオブジェクトの型。

defaultNamespace

すべての XML 要素使用する既定名前空間

使用例使用例

Widget という名前のシンプルなオブジェクトシリアル化する XmlSerializer構築例を次に示します。この例では、オブジェクト各種プロパティ設定してから Serialize メソッド呼び出します。

Private Sub SerializeObject(ByVal
 filename As String)
    Dim serializer As New
 XmlSerializer(GetType(OrderedItem), _
                                          "http://www.cpandl.com")
    
    ' Create an instance of the class to be serialized.
    Dim i As New OrderedItem()
    
    ' Insert code to set property values.
    ' Writing the document requires a TextWriter.
    Dim writer As New StreamWriter(filename)
    ' Serialize the object, and close the TextWriter.
    serializer.Serialize(writer, i)
    writer.Close()
End Sub


Private Sub DeserializeObject(ByVal
 filename As String)
    Dim serializer As New
 XmlSerializer(GetType(OrderedItem), _
                                          "http://www.cpandl.com")
    ' 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 i As OrderedItem
    
    ' Deserialize the object.
    i = CType(serializer.Deserialize(fs), OrderedItem)
    ' Insert code to use the properties and methods of the object.
End Sub
     
private void SerializeObject(string
 filename) {
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem), "http://www.cpandl.com");
     
    // Create an instance of the class to be serialized.
    OrderedItem i = new OrderedItem();
     
    // Insert code to set property values.
     
    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);
    // Serialize the object, and close the TextWriter
    serializer.Serialize(writer, i);
    writer.Close();
}
 
private void DeserializeObject(string
 filename) {
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem), "http://www.cpandl.com");
    // 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.
    OrderedItem i;
     
    // Deserialize the object.
    i = (OrderedItem) serializer.Deserialize(fs);
     
    // Insert code to use the properties and methods of the object.
}

private:
   void SerializeObject( String^ filename )
   {
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,"http://www.cpandl.com" );

      // Create an instance of the class to be serialized.
      OrderedItem^ i = gcnew OrderedItem;

      // Insert code to set property values.

      // Writing the document requires a TextWriter.
      TextWriter^ writer = gcnew StreamWriter( filename );
      // Serialize the object, and close the TextWriter
      serializer->Serialize( writer, i );
      writer->Close();
   }

   void DeserializeObject( String^ filename )
   {
      XmlSerializer^ serializer = gcnew XmlSerializer(
         OrderedItem::typeid,"http://www.cpandl.com" );
      // 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.
      OrderedItem^ i;

      // Deserialize the object.
      i = dynamic_cast<OrderedItem^>(serializer->Deserialize( fs ));

      // Insert code to use the properties and methods of the object.
   }
private void SerializeObject(String filename)
{
    XmlSerializer serializer =
        new XmlSerializer(OrderedItem.class.ToType()
,
        "http://www.cpandl.com");

    // Create an instance of the class to be serialized.
    OrderedItem i = new OrderedItem();

    // Insert code to set property values.
    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);

    // Serialize the object, and close the TextWriter
    serializer.Serialize(writer, i);
    writer.Close();
} //SerializeObject

private void DeserializeObject(String filename)
{
    XmlSerializer serializer =
        new XmlSerializer(OrderedItem.class.ToType()
,
        "http://www.cpandl.com");

    // 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.
    OrderedItem i;

    // Deserialize the object.
    i = (OrderedItem)serializer.Deserialize(fs);
    // Insert code to use the properties and methods of the object.
} //DeserializeObject    
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

XmlSerializer コンストラクタ

XmlSerializer クラス新しインスタンス初期化します。
オーバーロードの一覧オーバーロードの一覧

名前 説明
XmlSerializer () XmlSerializer クラス新しインスタンス初期化します。

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

XmlSerializer (XmlTypeMapping) ある型を別の型に割り当てるオブジェクト指定してXmlSerializer クラスインスタンス初期化します。

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

関連項目

XmlSerializer クラス
XmlSerializer メンバ
System.Xml.Serialization 名前空間

XmlSerializer メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド CanDeserialize XmlSerializer が、指定されXML ドキュメントを逆シリアル化できるかどうかを示す値を取得します
パブリック メソッド Deserialize オーバーロードされますXML ドキュメントを逆シリアル化ます。
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド FromMappings オーバーロードされます指定した割り当てから XmlSerializer クラスインスタンス返します
パブリック メソッド FromTypes 型の配列から作成された、XmlSerializer オブジェクト配列返します
パブリック メソッド GenerateSerializer オーバーロードされます。 型指定されたシリアライザを格納しているアセンブリ返します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド GetXmlSerializerAssemblyName オーバーロードされます特定の型のシリアル化または逆シリアル化のために特に作成され1 つ上のバージョンXmlSerializer格納しているアセンブリの名前を返します
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド Serialize オーバーロードされますオブジェクトXML ドキュメントシリアル化ます。
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

XmlSerializer クラス
System.Xml.Serialization 名前空間
XmlAttributeOverrides クラス
XmlAttributes クラス
XmlSerializer クラス
XmlAttributes.XmlText プロパティ
XmlAttributes クラス

その他の技術情報

XML シリアル化概要
方法 : XML ストリーム代替要素名を指定する
属性使用した XML シリアル化制御
XML シリアル化の例
XML スキーマ定義ツール (Xsd.exe)
方法 : 派生クラスシリアル化制御する
<dateTimeSerialization> 要素
<xmlSerializer> 要素

XmlSerializer メンバ

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

XmlSerializer データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
プロテクト コンストラクタプロテクト コンストラクタ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド CanDeserialize XmlSerializer が、指定されXML ドキュメントを逆シリアル化できるかどうかを示す値を取得します
パブリック メソッド Deserialize オーバーロードされますXML ドキュメントを逆シリアル化ます。
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド FromMappings オーバーロードされます指定した割り当てから XmlSerializer クラスインスタンス返します
パブリック メソッド FromTypes 型の配列から作成された、XmlSerializer オブジェクト配列返します
パブリック メソッド GenerateSerializer オーバーロードされます。 型指定されたシリアライザを格納しているアセンブリ返します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド GetXmlSerializerAssemblyName オーバーロードされます特定の型のシリアル化または逆シリアル化のために特に作成され1 つ上のバージョンXmlSerializer格納しているアセンブリの名前を返します
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド Serialize オーバーロードされますオブジェクトXML ドキュメントシリアル化ます。
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
パブリック イベントパブリック イベント
  名前 説明
パブリック イベント UnknownAttribute シリアル化時に XmlSerializer不明な型の XML 属性認識した場合発生します
パブリック イベント UnknownElement シリアル化時に XmlSerializer不明な型の XML 要素認識した場合発生します
パブリック イベント UnknownNode シリアル化時に XmlSerializer不明な型の XML ノード認識した場合発生します
パブリック イベント UnreferencedObject SOAP エンコード済み XML ストリームの逆シリアル化時にXmlSerializer が、未使用の型または参照されていない型を認識した場合発生します
参照参照

関連項目

XmlSerializer クラス
System.Xml.Serialization 名前空間
XmlAttributeOverrides クラス
XmlAttributes クラス
XmlSerializer クラス
XmlAttributes.XmlText プロパティ
XmlAttributes クラス

その他の技術情報

XML シリアル化概要
方法 : XML ストリーム代替要素名を指定する
属性使用した XML シリアル化制御
XML シリアル化の例
XML スキーマ定義ツール (Xsd.exe)
方法 : 派生クラスシリアル化制御する
<dateTimeSerialization> 要素
<xmlSerializer> 要素



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「XmlSerializer」の関連用語

XmlSerializerのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



XmlSerializerのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS