Okay so I want to try to make a generic implementation to save settings of what could be many different types of generic objects. So say I have a class that is serializable of Person:
using System;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public class Person
{
[XmlAttribute]
public string PersonName { get; set; }
public Person(string name)
{
PersonName = name;
}
public Person() {}
}
And it serializes just fine like this:
<Person PersonName="Brett" />
But say I want to reproduce a pattern for saving many of these and also different structures that may be something like this:
<Order OrderId="1">
<SKU>Pants</SKU>
</Order>
I can also do that and it works fine. The problem is that I want to setup a container method so that I can assign a Name to the complex object and then have N numbers of them in a collection. I make up a generic class like so to do this:
using System;
using System.Runtime.Serialization;
using System.Xml.Serialization;
[Serializable]
public class SerializeContainer<T> where T : class, new()
{
[XmlAttribute]
public string Name { get; set; }
public T Setting { get; set; }
public SerializeContainer() { }
public SerializeContainer(string name, T setting)
{
if (!typeof(T).IsSerializable && ! typeof(ISerializable).IsAssignableFrom(typeof(T))))
{
throw new InvalidOperationException("A Serializable Type is required. Please ensure that the class used has the proper Serializable Attribute set.");
}
Name = name;
Setting = setting;
}
}
This serializes but the Node overrides my child node(T)'s root name with it's own like so:
<SerializeContainerOfPerson Name=\"Test\">
<Setting PersonName=\"Brett\" />
</SerializeContainerOfPerson>
But what I really want is to keep my original structure and just wrap around it like so:
<SerializeContainerOfPerson Name=\"Test\">
<Person PersonName=\"Brett\" />
</SerializeContainerOfPerson>
I have been trying to trick it with [XMLElementName(nameof(T))]. But of course that just renames the node to
<T ...
, so not really an answer. And due to the nature of the XML attribute adornments they have set rules so doing anything to find out the generic that I have tried doesn't work. Is there a way to do it or at least maybe I should go an interface route or another patter to basically do something that is reusable to keep the structure and just give it a name and serialize them both with keeping the structure intact.