方法: XML ストリームの代替要素名を指定する

XmlSerializer を使用して、クラスのセットが同じである XML ストリームを複数生成できます。 このような作業が必要になるのは、2 つの異なる XML Web サービスが、若干の違いのある同じ基本情報を要求するような場合です。 たとえば、書籍の注文を処理する 2 つの XML Web サービスがあり、どちらにも ISBN 番号が必要であるとします。 一方のサービスは <ISBN> タグを使用しますが、もう一方は <BookID> タグを使用します。 Book という名前のフィールドを含む、ISBN という名前のクラスがあります。 Book クラスのインスタンスがシリアル化されると、既定では、メンバー名 (ISBN) がタグ要素名として使用されます。 最初の XML Web サービスの場合、この既定どおりで問題ありません。 一方、2 つ目の XML Web サービスに XML ストリームを送信するには、タグの要素名が BookID になるようにシリアル化をオーバーライドする必要があります。

代替要素名で XML ストリームを作成するには

  1. XmlElementAttribute クラスのインスタンスを作成します。

  2. ElementNameXmlElementAttribute を "BookID" に設定します。

  3. XmlAttributes クラスのインスタンスを作成します。

  4. XmlElementAttribute オブジェクトを XmlElementsXmlAttributes プロパティによってアクセスされるコレクションに追加します。

  5. XmlAttributeOverrides クラスのインスタンスを作成します。

  6. XmlAttributesXmlAttributeOverrides に追加し、オーバーライドするオブジェクトの型とオーバーライドされるメンバーの名前を渡します。

  7. XmlSerializer を使用して、XmlAttributeOverrides クラスのインスタンスを作成します。

  8. Book クラスのインスタンスを作成し、シリアル化または逆シリアル化します。

Public Function SerializeOverride()  
    ' Creates an XmlElementAttribute with the alternate name.  
    Dim myElementAttribute As XmlElementAttribute = _  
    New XmlElementAttribute()  
    myElementAttribute.ElementName = "BookID"  
    Dim myAttributes As XmlAttributes = New XmlAttributes()  
    myAttributes.XmlElements.Add(myElementAttribute)  
    Dim myOverrides As XmlAttributeOverrides = New XmlAttributeOverrides()  
    myOverrides.Add(typeof(Book), "ISBN", myAttributes)  
    Dim mySerializer As XmlSerializer = _  
    New XmlSerializer(GetType(Book), myOverrides)  
    Dim b As Book = New Book()  
    b.ISBN = "123456789"  
    ' Creates a StreamWriter to write the XML stream to.  
    Dim writer As StreamWriter = New StreamWriter("Book.xml")  
    mySerializer.Serialize(writer, b);  
End Class  
public void SerializeOverride()  
{  
    // Creates an XmlElementAttribute with the alternate name.  
    XmlElementAttribute myElementAttribute = new XmlElementAttribute();  
    myElementAttribute.ElementName = "BookID";  
    XmlAttributes myAttributes = new XmlAttributes();  
    myAttributes.XmlElements.Add(myElementAttribute);  
    XmlAttributeOverrides myOverrides = new XmlAttributeOverrides();  
    myOverrides.Add(typeof(Book), "ISBN", myAttributes);  
    XmlSerializer mySerializer =
    new XmlSerializer(typeof(Book), myOverrides);
    Book b = new Book();  
    b.ISBN = "123456789";
    // Creates a StreamWriter to write the XML stream to.  
    StreamWriter writer = new StreamWriter("Book.xml");  
    mySerializer.Serialize(writer, b);  
}  

XML ストリームは、次のようになります。

<Book>  
    <BookID>123456789</BookID>  
</Book>  

関連項目