c# - deserialize XML file into a list error -
i writed follow generic code deserialize xml file 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 got the exception on desirialize action.
"an exception of type
system.invalidoperationexception
occurred in system.xml.dll not handled in user code"
this example 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 exception?
first of all, file should contain valid xml data serialized list<t>
object. e.g. if have serialized list of integers items 1 , 2 xml should 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 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 empty or has invalid data invalidoperationexception
during deserialization attempt. read property message
of exception details. e.g. if file empty, root element missing.
note: when working unmanaged resources it's better use using
construct 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); }
Comments
Post a Comment