Export (0) Print
Expand All

How to: Read Object Data from an XML File (C# and Visual Basic)

This example reads object data that was previously written to an XML file using the XmlSerializer class.

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more information, see How to: Insert IntelliSense Code Snippets.


    public class Book
    {
        public String title;
    }       

public void ReadXML()
{
    System.Xml.Serialization.XmlSerializer reader = 
        new System.Xml.Serialization.XmlSerializer(typeof(Book));
    System.IO.StreamReader file = new System.IO.StreamReader(
        @"c:\temp\SerializationOverview.xml");
    Book overview = new Book();
    overview = (Book)reader.Deserialize(file);

    Console.WriteLine(overview.title);

}


Replace the file name "c:\IntroToVB.xml" with the name of the file containing the serialized data. For more information about serializing data, see How to: Write Object Data to an XML File (C# and Visual Basic).

The class must have a public constructor without parameters.

Only public properties and fields are deserialized.

The following conditions may cause an exception:

  • The class being serialized does not have a public, parameterless constructor.

  • The data in the file does not represent data from the class to be deserialized.

  • The file does not exist (IOException).

Always verify inputs, and never deserialize data from an untrusted source. The re-created object runs on a local computer with the permissions of the code that deserialized it. Verify all inputs before using the data in your application.

Community Additions

ADD
Show:
© 2014 Microsoft