次の方法で共有


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
    シリアル化するオブジェクトの型。

解説

フィールドとプロパティを XML にエンコードする方法を制御するには、overrides パラメータを使用します。これらの設定値により、オブジェクトに既に存在する属性がオーバーライドされます。この機能は、ソース コードを変更できないときや、同一のクラスに複数のエンコーディングが必要なときに役立ちます。

使用例

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

プラットフォーム

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。

バージョン情報

.NET Framework

サポート対象 : 2.0、1.1、1.0

.NET Compact Framework

サポート対象 : 2.0

参照

関連項目

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

その他の技術情報

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