利用 XmlSerializer,你可以產生多個包含相同類別的 XML 串流。 你可能想這麼做,因為兩個不同的 XML Web 服務需要相同的基本資訊,只有細微差異。 舉例來說,想像有兩個 XML 網路服務處理書籍訂單,因此都需要 ISBN 編號。 一個服務使用標籤 <ISBN> ,另一個使用標籤 <BookID>。 你有一個名為 Book 的類別,裡面包含一個名為 ISBN的欄位。 當類別實例 Book 被序列化時,預設會使用成員名稱(ISBN)作為標籤元素名稱。 對於第一個 XML Web 服務,這符合預期。 但若要將 XML 串流傳送到第二個 XML 網路服務,您必須覆寫序列化,使標籤的元素名稱為 BookID。
建立一個包含替代元素名稱的 XML 串流
建立一個類別 XmlElementAttribute 的實例。
將XmlElementAttributeElementName設定為「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>