Miles Chen
Miles Chen

Reputation: 793

IXmlSerializable and XmlRootAttribute

I have a weird requirement on xml serialization.

Refer the following C# code (which cannot be compiled due to the variable 'rootName' is out of scope). My intention is to make my class GeneralData be 'general'. Which means this class can be serialized to different XML strings with different root element according to the input parameter for the class constructor.

[XmlRoot(ElementName = rootName)]
public class GeneralData : Dictionary<String, Object>, IXmlSerializable
{
    public string rootName;
    public GeneralData(string rootName)
    {
        this.rootName = rootName;
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        foreach (var key in Keys)
        {
            var value = base[key];
            writer.WriteElementString(key, value.ToString());
        }
    }
}

Anyone can help me to accomplish the task? Maybe in a totally different way? Thanks in advance!!

Upvotes: 1

Views: 972

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062660

IXmlSerializable does not get to control the root element. So no, you can't really do that. The closest you could do would be to use new XmlSerializer(...) with the overload that lets you specify the root name at runtime (into the constructor), but you should be cautious: the non-trivial constructors of XmlSerializer do not use the inbuilt serializer-cache, meaning: you can end up creating a new assembly per new XmlSerializer(...), and assemblies are never unloaded. This can lead to memory leak issues if you don't add your own caching layer for the serializer instances.

Upvotes: 4

Related Questions