IXmlSerializable.ReadXml(XmlReader) 方法


从其 XML 表示形式生成对象。Generates an object from its XML representation.

 void ReadXml(System::Xml::XmlReader ^ reader);
public void ReadXml (System.Xml.XmlReader reader);
abstract member ReadXml : System.Xml.XmlReader -> unit
Public Sub ReadXml (reader As XmlReader)



从中对对象进行反序列化的 XmlReader 流。The XmlReader stream from which the object is deserialized.


下面的示例演示方法的实现 ReadXmlThe following example illustrates an implementation of the ReadXml method.

virtual void ReadXml( XmlReader^ reader )
   personName = reader->ReadString();
public void ReadXml (XmlReader reader)
    personName = reader.ReadString();

下面的示例演示 XmlSerializer 如何使用类反序列化此对象。The following example illustrates the use of the XmlSerializer class to deserialize this object.

#using <System.Xml.dll>
#using <System.dll>
#using <Person.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;

int main()
   XmlSerializer^ serializer = gcnew XmlSerializer( Person::typeid );
   FileStream^ file = gcnew FileStream( "test.xml",FileMode::Open );
   Person^ aPerson = dynamic_cast<Person^>(serializer->Deserialize( file ));
   Console::WriteLine( aPerson );
using System;
using System.IO;
using System.Xml.Serialization;

public class Reader {

  public static void Main() {
    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    FileStream file = new FileStream("test.xml", FileMode.Open);
    Person aPerson = (Person) serializer.Deserialize(file);


ReadXml方法必须使用方法编写的信息重建您的对象 WriteXmlThe ReadXml method must reconstitute your object using the information that was written by the WriteXml method.

调用此方法时,读取器将定位在包装您的类型的信息的开始标记上。When this method is called, the reader is positioned on the start tag that wraps the information for your type. 也就是说,直接在指示序列化对象开始的开始标记上。That is, directly on the start tag that indicates the beginning of a serialized object. 此方法返回时,它必须读取从开始到结尾的整个元素,包括其所有内容。When this method returns, it must have read the entire element from beginning to end, including all of its contents. WriteXml 方法不同,框架不会自动处理包装元素。Unlike the WriteXml method, the framework does not handle the wrapper element automatically. 你的实现必须这样做。Your implementation must do so. 未能遵守这些定位规则可能会导致代码生成意外的运行时异常或数据损坏。Failing to observe these positioning rules may cause code to generate unexpected runtime exceptions or corrupt data.

实现此方法时,应考虑到恶意用户可能会提供格式正确但无效的 XML 表示形式,以便禁用或更改应用程序的行为。When implementing this method, you should consider the possibility that a malicious user might provide a well-formed but invalid XML representation in order to disable or otherwise alter the behavior of your application.