返回介绍

如何:指定 XML 流的替代元素名称

发布于 2025-02-23 23:16:25 字数 3828 浏览 0 评论 0 收藏 0

代码示例

使用 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 流

  1. 创建 XmlElementAttribute 类的一个实例。
  2. 将 ElementName 的 XmlElementAttribute 设置为 BookID
  3. 创建 XmlAttributes 类的一个实例。
  4. 向通过 XmlElementAttribute 的 XmlElements 属性访问的集合中添加 XmlAttributes 对象。
  5. 创建 XmlAttributeOverrides 类的一个实例。
  6. XmlAttributes 添加至 XmlAttributeOverrides ,同时传递要重写的对象类型以及要被重写的成员名称。
  7. XmlSerializer 创建 XmlAttributeOverrides 类的实例。
  8. 创建 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>  

另请参阅

XmlElementAttribute
XmlAttributes
XmlAttributeOverrides
XML 和 SOAP 序列化
XmlSerializer
如何:序列化对象
如何:反序列化对象
如何:反序列化对象

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文