如何:为 XML 流指定备用元素名称

使用XmlSerializer,您可以使用同一组类生成多个 XML 流。 你可能想要执行此作,因为两个不同的 XML Web 服务需要相同的基本信息,只有轻微的差异。 例如,假设有两个 XML Web 服务处理书籍订单,因此两者都需要 ISBN 数字。 一个服务使用标记 <ISBN> ,而第二个服务使用标记 <BookID>。 你有一个名为Book的类,其中包含一个名为ISBN的字段。 在序列化 Book 类的实例时,默认情况下,它会使用成员名称(ISBN)作为标记元素的名称。 对于第一个 XML Web 服务,这与预期相同。 但是,若要将 XML 流发送到第二个 XML Web 服务,必须重写序列化,以便标记的元素名称为 BookID

为了创建一个使用备用元素名称的 XML 流

  1. 创建类的 XmlElementAttribute 实例。

  2. XmlElementAttributeElementName设置为“BookID”。

  3. 创建类的 XmlAttributes 实例。

  4. 将对象添加到通过 XmlElementAttribute 属性访问的 XmlElementsXmlAttributes 集合中。

  5. 创建类的 XmlAttributeOverrides 实例。

  6. XmlAttributes 添加到 XmlAttributeOverrides,并传递要重写的对象的类型以及被重写成员的名称。

  7. 创建XmlAttributeOverrides类的XmlSerializer实例。

  8. 创建类的 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>

另请参阅