0

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?

1 Answer 1

1

Creating the xml using Serialize is not required for successful serialization, but is useful to determine if your xml looks like it should. A serialized empty collection should look more like:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEmployee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.