IXmlSerializable and XmlRootAttribute

I have a weird requirement for serializing XML.

Refer to the following C # code (which cannot be compiled because the "rootName" variable is out of scope). I intend to make my GeneralData class "general." This means that this class can be serialized into different XML lines with a different root element in accordance with 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());
        }
    }
}

Can anyone help me complete the task? Maybe in a completely different way? Thanks in advance!

+1
source share
1 answer

IXmlSerializable . , . , , new XmlSerializer(...) , ( ), : XmlSerializer serializer-cache, : new XmlSerializer(...), . , .

+3

Source: https://habr.com/ru/post/1621960/


All Articles