代码示例
使用 XmlSerializer,可以用同一组类生成多个 XML 流。您可能希望这样做,原因是两个不同的 XML Web 服务需要同样的基本信息,而只有微小差异。例如,假定有两个处理图书订单的 XML Web 服务,这两者都需要 ISBN 编号。一个服务使用 <ISBN> 标记,而另一个使用 <BookID> 标记。您有一个名为 Book 的类,其中包含一个名为 ISBN 的字段。默认情况下,当 Book 类的一个实例被序列化时,会将成员名 (ISBN) 用作标记元素名。对于第一个 XML Web 服务来说,应当这样做。但是要将 XML 流发送给第二个 XML Web 服务,必须重写序列化,以使标记的元素名成为 BookID。
用备用元素名创建 XML 流
创建 XmlElementAttribute 类的实例。
将 XmlElementAttribute 的 ElementName 设置为“BookID”。
创建 XmlAttributes 类的实例。
将 XmlElementAttribute 对象添加到通过 XmlAttributes 的 XmlElements 属性访问的集合。
创建 XmlAttributeOverrides 类的实例。
将 XmlAttributes 添加到 XmlAttributeOverrides,并传递要重写的对象的类型和被重写的成员的名称。
使用 XmlAttributeOverrides 创建 XmlSerializer 类的实例。
创建
Book类的实例,并对其进行序列化或反序列化。
示例
Public Class 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 class 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>
请参见
任务
如何:将对象序列化
如何:将对象反序列化
如何:将对象反序列化
参考
XmlSerializer
XmlElementAttribute
XmlAttributes
XmlAttributeOverrides