Search code examples
c#serializationxmlreaderxmlwriter

How to read/write complex object with XmlWriter/XmlReader


I've been trying to find an easy way to write XML using the XmlReader/XmlWriter. I don't really like using the interface "IXmlSerializable", but I've got no choice for some of my dataclass.

Anyway, what I want to do is quite simple:

private MyClass myObject;
public void WriteXml(XmlWriter writer)
{
    writer.WriteObject(myObject); // <-- this method doesn't exists
}

So, I found 2 work around:

  1. Write my own routine to write my object manually. Quite ridiculous since .Net already does it.
  2. Create a new serializer using a StringWriter and use the WriteValue(string) method.

I haven't tested the second yet but I think it will probably work (not sure because of the ReadValue result).

Then my question is: Am I missing something important or is it the only way? Or is there a better way to handle that?

Thanks.


Solution

  • After playing around, I found something quite simple. Here is the code I was playing with for those who are wondering how I fixed my problem (similar for reading and element):

        public static void WriteElement(XmlWriter writer, string name, object value)
        {
            var serializer = new XmlSerializer(value.GetType(), new XmlRootAttribute(name));
            serializer.Serialize(writer, value);
        }
    

    I don't know why I was complicating the problem, but it cannot be more simpler than that.