Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exception when deserializing xml file in C#

Class:

namespace Biftek
{
    [XmlRoot("Users")]
   
    public class User
    {
        public string username { get; set; }
        public string password { get; set; }
    }
    public class UserManager
    {
        public static List<User> Load(string path)
        {
            List<User> users = new List<User>();
            if(File.Exists(path))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<User>));
                using (XmlReader reader = XmlReader.Create(path))
                {
                    users = (List<User>)serializer.Deserialize(reader);
                }
            }
            return users;
        }
    }
}

XML File:

<?xml version="1.0" encoding="utf-8" ?>
<Users>
    <User>
        <username>admin</username>
        <password>admin</password>
    </User>
    <User>
        <username>user</username>
        <password>user</password>
    </User>
</Users>

Exceptions:
System.InvalidOperationException: ‘There is an error in XML document (2, 2).’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Inner Exception
InvalidOperationException: < Users xmlns=”> was not expected.

>Solution :

In your code, the XmlSerializer is expecting to deserialize a List, but your XML file is structured with a root element that contains user elements.

namespace Biftek
{
    [XmlRoot("Users")]
    public class UsersList
    {
        [XmlElement("User")]
        public List<User> Users { get; set; } = new List<User>();
    }

   public class User
   {
        public string username { get; set; }
        public string password { get; set; }
    }

    public class UserManager
    {
        public static List<User> Load(string path)
        {
            UsersList usersList = new UsersList();
            if(File.Exists(path))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(UsersList));
                using (XmlReader reader = XmlReader.Create(path))
                {
                    usersList = (UsersList)serializer.Deserialize(reader);
                }
            }
            return usersList.Users;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading