XmlSerializerを使用すると、同じクラス セットを使用して複数の XML ストリームを生成できます。 これは、2 つの異なる XML Web サービスに同じ基本情報が必要で、わずかな違いしかないためです。 たとえば、書籍の注文を処理し、両方に ISBN 番号が必要な 2 つの XML Web サービスがあるとします。 1 つのサービスはタグ <ISBN> を使用し、2 つ目のサービスではタグ <BookID>を使用します。
Bookという名前のフィールドを含む ISBN という名前のクラスがあります。
Book クラスのインスタンスがシリアル化されるときに、既定では、メンバー名 (ISBN) をタグ要素名として使用します。 最初の XML Web サービスの場合、これは想定どおりに行われます。 ただし、2 番目の XML Web サービスに XML ストリームを送信するには、タグの要素名が BookIDされるようにシリアル化をオーバーライドする必要があります。
代替要素名を使用して XML ストリームを作成するには
XmlElementAttribute クラスのインスタンスを作成します。
ElementNameのXmlElementAttributeを "BookID" に設定します。
XmlAttributes クラスのインスタンスを作成します。
XmlElementAttributeの XmlElements プロパティを使用してアクセスするコレクションにXmlAttributes オブジェクトを追加します。XmlAttributeOverrides クラスのインスタンスを作成します。
XmlAttributesにXmlAttributeOverridesを追加し、オーバーライドするオブジェクトの型とオーバーライドされるメンバーの名前を渡します。XmlSerializerを使用して、XmlAttributeOverridesクラスのインスタンスを作成します。Bookクラスのインスタンスを作成し、シリアル化または逆シリアル化します。
Example
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>
こちらも参照ください
.NET