mardi 7 avril 2015

Error in xml file using the XmlSerializer

I have an website with a administrator page. On this page a user is able to create, update or delete employees. I want to save these employees in a xml file using the XmlSerializer of C#.


The employee class looks like this:



public class Employee
{
public int id { get; set; }
public String lastname { get; set; }
public String firstname { get; set; }
public String enterdate { get; set; }
public int salarylevel { get; set; }
}


However, I get an error while reading the xml file and do not know what to do:



In System.InvalidOperationException is an exception of type "System.Xml.dll" occurred, but this was not in the user code processed.


Additional information: error in XML document (0,0).



Translated from german.


I created the project as an empty WebAPI and I have an EmployeeController that looks like this:



public class EmployeeController : ApiController
{
List<Employee> employeelist = new List<Employee>();

[HttpGet]
public IEnumerable<Employee> getEmployees()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Employee>));
FileStream stream = new FileStream(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "employees.xml", FileMode.Open);
employeelist = (List<Employee>)serializer.Deserialize(stream);

return employeelist;
}
}


The error occurs at: employeelist = (List<Employee>)serializer.Deserialize(stream);


The controller gets called with JQuery and the getJSON method using the url http://localhost:5267/api/employee/. All employees should be saved in a xml file that is called employees.xml which contains only one line at the moment:



<?xml version="1.0" encoding="utf-8" ?>


What I expected to happen was, that I get an empty list because there are no related xml elements in the file and therefore the page shows no employees.


I guess that I messed it up because I created the xml file manually and without the serializer or that the serializer cannot handle the one line xml. Does someone know how I should solve this problem?





Aucun commentaire:

Enregistrer un commentaire