Read to XML file to custom defined objects

05 Feb

Suppose we have an XML file and we would like to read it into custom defined objects:


We hope to read the data to a List<VoiceCmdItem> variable, so it is straightforward to come up a class VoiceCmdItem:


Note that the propery name does not exactly correspond to the XML element name, and this will not work in the process of deserialization. To make the property names match the XML element, we can use the XmlElement attributes. In addition, the class should be decroated with the attribute Serializable and a default constructor is also needed. The implemented class should like this:


Note that if you wish to read the XML file to generic collections, the root node of the XML file must be in the form of ArrayOfXxx , where the Xxx refers to the element in the collection (i.e. VoiceCmdItem in our case). Otherwise, there will be an exception when serializing it into a generic collection instance. The detailed exception might be in the form of “System.InvalidOperationException: There is an error in XML document (2, 2). —> System.InvalidOperationException: <SomeOtherRootElementName xmlns=”> was not expected.” .

The code to serialize this XML file to a List<T> might be like this:

XmlSerializer x = new XmlSerializer(CmdList.GetType());
using (FileStream fs = new FileStream(FilePath, FileMode.Open))
XmlReader reader = new XmlTextReader(fs);
CmdList = (List<VoiceCmdItem>)x.Deserialize(reader);

Leave a comment

Posted by on February 5, 2009 in Dotnet/C#


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: