如何:指定 XML 流的替代元素名称
代码示例
使用 XmlSerializer 可以用同一组类生成多个 XML 流。由于两个不同的 XML Web services 需要的基本信息相同(略有差异),因此您或许希望用同一组类生成多个 XML 流。例如,假设有两个处理书籍订单的 XML Web services,它们都需要 ISBN 号。一个服务使用标记 <ISBN>,而另一个使用标记 <BookID>。您已经有一个名为 Book
的类,其中包含名为 ISBN
的字段。当序列化 Book
类的实例时,该实例将在默认情况下使用成员名称 (ISBN) 作为标记元素名称。对于第一个 XML Web services,以上行为与预期相同。但如果要将 XML 流发送至第二个 XML Web services,则必须重写序列化,以便使标记的元素名称采用 BookID
。
用替代元素名称创建 XML 流
创建 XmlElementAttribute 类的实例。
将 XmlElementAttribute 的 ElementName 设置为“BookID”。
创建 XmlAttributes 类的实例。
向通过 XmlAttributes 的 XmlElements 属性访问的集合中添加 XmlElementAttribute 对象。
创建 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
其他资源
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。