C# XmlSerializer, edit XML file without rewriting the whole file

I am currently working on a C# app, that has to serialize some simple object into a given XML file.

For example, here is a simple example class... Let's say Human

   public class Human
    {
        private XmlSerializer serializer = new XmlSerializer(typeof(Human));

        public string name { get; set; }
        public int age { get; set; }
        public string country { get; set; }

        public void Serialize()
        {
            StreamWriter stream = null;

            try
            {
                stream = new StreamWriter("data.xml");
                serializer.Serialize(stream, this);
                stream.Close();
            }
            catch (Exception e)
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
    }

If I instanciate this class, set some values, and call the Serialize() method, my data.xml file will look as follows :

<?xml version="1.0" encoding="utf-8"?>
<Human xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>Oscar</name>
  <age>20</age>
  <country>France</country>
</Human>

Now imagine that I have an object that contains a List of Human. Serializing this object will take time and ressources, and will generate a pretty big XML file.

If I wan't to edit a specific Human, or simply add a new one to my List, is there a way to edit/modify only a small part of the XML file ? Or do I have to re-serialize again the whole List and replace the XML file content ?

Jon Skeet
people
quotationmark

XML simply isn't designed for this sort of operation. Your options are probably:

  • Live with the file being big
  • Use multiple files instead
  • Use some other persistence (non-XML files, or a database) instead

Without knowing how big you mean by "big" or what your performance requirements are, it's hard to say which of these options is the most suitable - but I'd strongly urge you to carefully consider what your actual requirements are in concrete terms, and test them with the simplest option available.

people

See more on this question at Stackoverflow