XmlElementAttribute クラスとは? わかりやすく解説

XmlElementAttribute クラス

パブリック フィールドパブリック プロパティ保持するオブジェクトを XmlSerializer がシリアル化または逆シリアル化するときに、それらのフィールドプロパティXML 要素を表すかどうか示します

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

<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field
 Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue,
 AllowMultiple:=True)> _
Public Class XmlElementAttribute
    Inherits Attribute
Dim instance As XmlElementAttribute
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue,
 AllowMultiple=true)] 
public class XmlElementAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Property|AttributeTargets::Field|AttributeTargets::Parameter|AttributeTargets::ReturnValue,
 AllowMultiple=true)] 
public ref class XmlElementAttribute : public
 Attribute
/** @attribute AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue,
 AllowMultiple=true) */ 
public class XmlElementAttribute extends Attribute
AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue,
 AllowMultiple=true) 
public class XmlElementAttribute extends
 Attribute
解説解説

XmlElementAttribute は、XmlSerializerオブジェクトシリアル化または逆シリアル化する方法制御する一連の属性1 つです。類似する属性の完全な一覧については、「XML シリアル化制御する属性」を参照してください

通常XML ドキュメントには XML 要素含まれており、各 XML 要素は、開始タグ終了タグタグ間のデータという 3 つの部分構成されています。XML タグ入れ子できます。つまり、タグ間のデータXML 要素になっている場合あります。これにより、ある要素別の要素を囲むことができるため、ドキュメントデータ階層的に格納できますXML 要素には、属性を含むこともできます

要素名や名前空間など、XML 要素特性制御するには、XmlElementAttributeパブリック フィールドまたは読み取り/書き込み可能なパブリック プロパティ適用します。

XmlElementAttribute は、オブジェクト配列返すフィールドには何回でも適用できます。その理由は、その配列挿入できる各種の型を、Type プロパティ使用して指定できるようにするためです。たとえば、次の C# コード配列には、文字列整数両方格納できます

 public class Things{
    [XmlElement(DataType = typeof(string)),
    XmlElement(DataType = typeof(int))]
    public object[] StringsAndInts;
 }

結果として次のような XML生成されます。

 <Things>
    <string>Hello</string>
    <int>999</int>
    <string>World</string>
 </Things>

ElementName プロパティの値を指定せずに XmlElementAttribute何回適用した場合各要素には、配列挿入できるオブジェクトの型の名前が付けられます。

配列返すフィールドまたはプロパティXmlElementAttribute適用すると、その配列内の項目は XML 要素シーケンスとしてエンコードされます

これに対しこのようなフィールドまたはプロパティXmlElementAttribute適用しないと、それらが返す配列内の項目は単なる要素シーケンスとしてエンコードされ、それぞれフィールドまたはプロパティの名前が付いた要素として入れ子なります配列シリアル化方法制御する場合は、XmlArrayAttribute 属性と XmlArrayItemAttribute 属性使用します

Type プロパティ設定して、元のフィールドまたはプロパティ (XmlElementAttribute適用したフィールドまたはプロパティ) の型から派生する型を指定できます

フィールドまたはプロパティが ArrayList を返す場合は、そのメンバXmlElementAttribute複数インスタンス適用できます。各インスタンスType プロパティに、配列挿入できるオブジェクトの型を設定します

属性使用方法については、「属性使用したメタデータ拡張」を参照してください

メモメモ

コードでは、XmlElementAttribute代わりに XmlElement という短い語使用できます

使用例使用例

Group という名前のクラスシリアル化し、そのメンバいくつかXmlElementAttribute適用する例を次に示しますEmployees という名前のフィールドは、Employee オブジェクト配列返します。この例では、XmlElementAttribute は、結果として生成される XML入れ子にしないよう指定してます。これは、配列内の項目の既定動作です。

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


Public Class Group
    ' Set the element name and namespace of the XML element.
    <XmlElement(ElementName := "Members", _
     Namespace := "http://www.cpandl.com")>
 _    
    Public Employees() As Employee
    
    <XmlElement(DataType := "double", _
     ElementName := "Building")> _
    Public GroupID As Double
    
    <XmlElement(DataType := "hexBinary")> _
    Public HexBytes() As Byte
    
    <XmlElement(DataType := "boolean")> _
    Public IsActive As Boolean
    
    <XmlElement(GetType(Manager))> _
    Public Manager As Employee
    
    <XmlElement(GetType(Integer), _
        ElementName := "ObjectNumber"), _
     XmlElement(GetType(String), _
        ElementName := "ObjectString")> _
    Public ExtraInfo As ArrayList
End Class

Public Class Employee
    Public Name As String
End Class

Public Class Manager
    Inherits Employee
    Public Level As Integer
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New
 Run()
        test.SerializeObject("FirstDoc.xml")
        test.DeserializeObject("FirstDoc.xml")
    End Sub
    
    Public Sub SerializeObject(filename As
 String)
        ' Create the XmlSerializer.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' To write the file, a TextWriter is required.
        Dim writer As New
 StreamWriter(filename)
        
        ' Create an instance of the group to serialize, and set
        ' its properties. 
        Dim group As New
 Group()
        group.GroupID = 10.089f
        group.IsActive = False
        
        group.HexBytes = New Byte() {Convert.ToByte(100)}
        
        Dim x As New Employee()
        Dim y As New Employee()
        
        x.Name = "Jack"
        y.Name = "Jill"
        
        group.Employees = New Employee() {x, y}
        
        Dim mgr As New Manager()
        mgr.Name = "Sara"
        mgr.Level = 4
        group.Manager = mgr
        
        ' Add a number and a string to the
        ' ArrayList returned by the ExtraInfo property. 
        group.ExtraInfo = New ArrayList()
        group.ExtraInfo.Add(42)
        group.ExtraInfo.Add("Answer")
        
        ' Serialize the object, and close the TextWriter.      
        s.Serialize(writer, group)
        writer.Close()
    End Sub    
    
    Public Sub DeserializeObject(filename As
 String)
        Dim fs As New FileStream(filename,
 FileMode.Open)
        Dim x As New XmlSerializer(GetType(Group))
        Dim g As Group = CType(x.Deserialize(fs),
 Group)
        Console.WriteLine(g.Manager.Name)
        Console.WriteLine(g.GroupID)
        Console.WriteLine(g.HexBytes(0))

        Dim e As Employee
        For Each e In g.Employees
            Console.WriteLine(e.Name)
        Next e
    End Sub
End Class

using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Set the element name and namespace of the XML element.
   By applying an XmlElementAttribute to an array,  you instruct
   the XmlSerializer to serialize the array as a series of XML
   elements, instead of a nested set of elements. */
   
   [XmlElement(
   ElementName = "Members",
   Namespace = "http://www.cpandl.com")]
   public Employee[] Employees;
      
   [XmlElement(DataType = "double",
   ElementName = "Building")]
   public double GroupID;

   [XmlElement(DataType = "hexBinary")]
   public byte [] HexBytes;


   [XmlElement(DataType = "boolean")]
   public bool IsActive;

   [XmlElement(Type = typeof(Manager))]
   public Employee Manager;

   [XmlElement(typeof(int),
   ElementName = "ObjectNumber"),
   XmlElement(typeof(string),
   ElementName = "ObjectString")]
   public ArrayList ExtraInfo;
}   

public class Employee
{
   public string Name;
}

public class Manager:Employee{
   public int Level;
}

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


   public void SerializeObject(string
 filename)
   {
      // Create the XmlSerializer.
      XmlSerializer s = new XmlSerializer(typeof(Group));

      // To write the file, a TextWriter is required.
      TextWriter writer = new StreamWriter(filename);

      /* Create an instance of the group to serialize, and set
         its properties. */
      Group group = new Group();
      group.GroupID = 10.089f;
      group.IsActive = false;
      
      group.HexBytes = new byte[1]{Convert.ToByte(100)};

      Employee x = new Employee();
      Employee y = new Employee();

      x.Name = "Jack";
      y.Name = "Jill";
      
      group.Employees = new Employee[2]{x,y};

      Manager mgr = new Manager();
      mgr.Name = "Sara";
      mgr.Level = 4;
      group.Manager = mgr;

      /* Add a number and a string to the 
      ArrayList returned by the ExtraInfo property. */
      group.ExtraInfo = new ArrayList();
      group.ExtraInfo.Add(42);
      group.ExtraInfo.Add("Answer");

      // Serialize the object, and close the TextWriter.      
      s.Serialize(writer, group);
      writer.Close();
   }

   public void DeserializeObject(string
 filename)
   {
      FileStream fs = new FileStream(filename, FileMode.Open);
      XmlSerializer x = new XmlSerializer(typeof(Group));
      Group g = (Group) x.Deserialize(fs);
      Console.WriteLine(g.Manager.Name);
      Console.WriteLine(g.GroupID);
      Console.WriteLine(g.HexBytes[0]);
      foreach(Employee e in g.Employees)
      {
         Console.WriteLine(e.Name);
      }
   }
}
   
#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Xml::Serialization;
public ref class Employee
{
public:
   String^ Name;
};

public ref class Manager: public
 Employee
{
public:
   int Level;
};

public ref class Group
{
public:

   /* Set the element name and namespace of the XML element.
      By applying an XmlElementAttribute to an array,  you instruct
      the XmlSerializer to serialize the array as a series of XML
      elements, instead of a nested set of elements. */

   [XmlElement(
   ElementName="Members",
   Namespace="http://www.cpandl.com")]
   array<Employee^>^Employees;

   [XmlElement(DataType="snippet1>",
   ElementName="Building")]
   double GroupID;

   [XmlElement(DataType="hexBinary")]
   array<Byte>^HexBytes;

   [XmlElement(DataType="boolean")]
   bool IsActive;

   [XmlElement(Type=::Manager::typeid)]
   Employee^ Manager;

   [XmlElement(Int32::typeid,
   ElementName="ObjectNumber"),
   XmlElement(String::typeid,
   ElementName="ObjectString")]
   ArrayList^ ExtraInfo;
};

void SerializeObject( String^ filename )
{
   // Create the XmlSerializer.
   XmlSerializer^ s = gcnew XmlSerializer( Group::typeid );

   // To write the file, a TextWriter is required.
   TextWriter^ writer = gcnew StreamWriter( filename );

   /* Create an instance of the group to serialize, and set
      its properties. */
   Group^ group = gcnew Group;
   group->GroupID = 10.089f;
   group->IsActive = false;
   array<Byte>^temp0 = {Convert::ToByte( 100 )};
   group->HexBytes = temp0;
   Employee^ x = gcnew Employee;
   Employee^ y = gcnew Employee;
   x->Name = "Jack";
   y->Name = "Jill";
   array<Employee^>^temp1 = {x,y};
   group->Employees = temp1;
   Manager^ mgr = gcnew Manager;
   mgr->Name = "Sara";
   mgr->Level = 4;
   group->Manager = mgr;

   /* Add a number and a string to the 
      ArrayList returned by the ExtraInfo property. */
   group->ExtraInfo = gcnew ArrayList;
   group->ExtraInfo->Add( 42 );
   group->ExtraInfo->Add( "Answer" );

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

void DeserializeObject( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   XmlSerializer^ x = gcnew XmlSerializer( Group::typeid );
   Group^ g = dynamic_cast<Group^>(x->Deserialize( fs ));
   Console::WriteLine( g->Manager->Name );
   Console::WriteLine( g->GroupID );
   Console::WriteLine( g->HexBytes[ 0 ] );
   IEnumerator^ myEnum = g->Employees->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Employee^ e = safe_cast<Employee^>(myEnum->Current);
      Console::WriteLine( e->Name );
   }
}

int main()
{
   SerializeObject( "FirstDoc.xml" );
   DeserializeObject( "FirstDoc.xml" );
}
import System.*;
import System.Collections.*;
import System.IO.*;
import System.Xml.Serialization.*;

public class Group
{
    /* Set the element name and namespace of the XML element.
       By applying an XmlElementAttribute to an array,  you instruct
       the XmlSerializer to serialize the array as a series of XML
       elements, instead of a nested set of elements. */
   
    /** @attribute XmlElement(ElementName = "Members",
        Namespace = "http://www.cpandl.com")
     */
    public Employee employees[];   
    /** @attribute XmlElement(DataType = "double", ElementName = "Building")
     */
    public double groupID;   
    /** @attribute XmlElement(DataType = "hexBinary")
     */
    public ubyte hexBytes[];   
    /** @attribute XmlElement(DataType = "boolean")
     */
    public boolean isActive;   
    /** @attribute XmlElement(Type = Manager.class)
     */
    public Employee manager;   
    /** @attribute XmlElement(int.class, ElementName
 = "ObjectNumber")
        @attribute XmlElement(String.class, ElementName = "ObjectString")
     */
    public ArrayList extraInfo;
} //Group

public class Employee
{
    public String name;
} //Employee

public class Manager extends Employee
{
    public int level;
} //Manager

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

    public void SerializeObject(String fileName)
    {
        // Create the XmlSerializer.
        XmlSerializer s = new XmlSerializer(Group.class.ToType());

        // To write the file, a TextWriter is required.
        TextWriter writer = new StreamWriter(fileName);

        /* Create an instance of the group to serialize, and set
           its properties. */
        Group group = new Group();
        group.groupID = 10.089f;
        group.isActive = false;
        group.hexBytes = new ubyte[] { Convert.ToByte(100) };

        Employee x = new Employee();
        Employee y = new Employee();

        x.name = "Jack";
        y.name = "Jill";
        group.employees = new Employee[] { x, y };

        Manager mgr = new Manager();
        mgr.name = "Sara";
        mgr.level = 4;
        group.manager = mgr;

        /* Add a number and a string to the 
           ArrayList returned by the ExtraInfo property. */
        group.extraInfo = new ArrayList();
        group.extraInfo.Add((Int32)42);
        group.extraInfo.Add("Answer");

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

    public void DeserializeObject(String fileName)
    {
        FileStream fs = new FileStream(fileName, FileMode.Open);
        XmlSerializer x = new XmlSerializer(Group.class.ToType());
        Group g = (Group)x.Deserialize(fs);

        Console.WriteLine(g.manager.name);
        Console.WriteLine(g.groupID);
        Console.WriteLine(g.hexBytes.get_Item(0));
        for (int iCtr = 0; iCtr < g.employees.length;
 iCtr++) {
            Employee e = g.employees[iCtr];
            Console.WriteLine(e.name);
        }
    } //DeserializeObject
} //Run
継承階層継承階層
System.Object
   System.Attribute
    System.Xml.Serialization.XmlElementAttribute
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlElementAttribute メンバ
System.Xml.Serialization 名前空間
XmlArrayAttribute クラス
XmlAttributeOverrides クラス
XmlAttributes クラス
XmlElementAttributes
XmlAttributes.XmlElements プロパティ
XmlRootAttribute
XmlSerializer
XmlAttributes クラス
その他の技術情報
XML シリアル化概要
方法 : XML ストリーム代替要素名を指定する
属性使用した XML シリアル化制御
XML シリアル化の例
XML スキーマ定義ツール (Xsd.exe)



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

辞書ショートカット

すべての辞書の索引

「XmlElementAttribute クラス」の関連用語

XmlElementAttribute クラスのお隣キーワード
検索ランキング

   

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



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

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

©2024 GRAS Group, Inc.RSS