1

i writed the follow generic code to deserialize an XML file into a list:

public List<T> getList<T>(string fPath)
{

    FileStream fs;
    fs = new FileStream(fPath, FileMode.Open);
    List<T> list;
    XmlSerializer xmls = new XmlSerializer(typeof(List<T>));
    list = (List<T>)xmls.Deserialize(fs);
    fs.Close();
    return list;
}

but i got the the Exception on the desirialize action.

"An exception of type System.InvalidOperationException occurred in System.Xml.dll but was not handled in user code"

this is an example for the XML file:

<?xml version="1.0"?>
<ArrayOfAdmin xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Admin>
    <MyUsername>User</MyUsername>
    <MyPassword>Pass</MyPassword>
  </Admin>
</ArrayOfAdmin>

whats cause the Exception?

Sefeli
  • 13
  • 3
  • Can you update your post to include a small XML file you would expect to be able to deserialize? – Nathan C Jan 28 '16 at 13:41
  • Hello Sefeli please check in this question : [http://stackoverflow.com/questions/608110/is-it-possible-to-deserialize-xml-into-listt](http://stackoverflow.com/questions/608110/is-it-possible-to-deserialize-xml-into-listt) – Ahmad Alloush Jan 28 '16 at 13:50
  • An XML file can only have a single Root Tag so it cannot be a collection. You want to deserialize the root which is tag "ArrayOfAdmin" not the child tag Admin. – jdweng Jan 28 '16 at 14:21

1 Answers1

2

First of all, your file should contain valid xml data with serialized List<T> object. E.g. if you have serialized list of integers with items 1 and 2 xml should look this way:

<?xml version="1.0"?>
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <int>1</int>
  <int>2</int>
</ArrayOfInt>

Or with your custom type:

<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Id>1</Id>
    <Name>Bob</Name>
  </Person>
  <Person>
    <Id>2</Id>
    <Name>Joe</Name>
  </Person>
</ArrayOfPerson>

When file is empty or it has invalid data you will get InvalidOperationException during deserialization attempt. Read property Message of this exception to get some details. E.g. if file is empty, it will say that root element is missing.

NOTE: When you are working with unmanaged resources it's better to use using construct to close/dispose such resources correctly in case of exception.

using (var stream = File.Open(fPath, FileMode.Open))
{
    var serializer = new XmlSerializer(typeof(List<T>));
    return (List<T>)serializer.Deserialize(stream);
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459