Not logged in - Login

Deserialize an XML file or string

The following illustrates how to deserialize an XML file and read it into an XML object structure.

// create a new file stream instance.
System.IO.FileStream fs = 
    new System.IO.FileStream(sImportFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);

// declare a variable to hold the entire XML file and read it in.
// Note: Create a custom fuction to read a FileStream and return a string object.
string sWholeXml = MyClass.ReadFileStream(fs);

// create our XML Serialization object. 
System.Xml.Serialization.XmlSerializer x = 
    new System.Xml.Serialization.XmlSerializer(typeof(OurRootNamespace.Order));

// create a text reader object that will be used in the Deserialize process 
System.IO.TextReader tr = new System.IO.StringReader(sWholeXml.ToString());

// deserialize the XML file and save to our object.
OurRootNamespace.Order objOrderList = (OurRootNamespace.Order)x.Deserialize(tr);

// close & dispose the text reader. 
tr.Close(); 
tr.Dispose();

// close the file stream.
fs.Close();

Note that the above can be done in fewer steps.

Create a StreamReader object based on the XML file.

Create an XML Serializer object based on the object type.

Then, calling the Deserialize() method, passing in the original StreamReader object (instead of the TextReader object in the first example).

BUT-

Doing it this way may cause special characters in the XML file to be translated incorrectly.

So... I'd recommend using the slightly longer approach outlined above.

Note: see this post for an example of a function that will read a FileStream object and return a string. http://wiki.devknight.com/wiki/30/create-a-function-to-read-a-filestream-and-return-a-string