I need to construct a set of dynamically created XML nodes from objects on the following format:
My Name
[Serializable]
public class DynamicSerializable : DynamicObject, ISerializable
{
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var kvp in dictionary)
{
info.AddValue(kvp.Key, kvp.Value);
}
}
}
[KnownType(typeof(DynamicSerializable))]
[DataContract]
public class Root
{
[DataMember]
public string Name { get; set; }
[DataMember]
public dynamic DynamicValues { get; set; }
}
Output:
<Program.Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://
schemas.datacontract.org/2004/07/">
<DynamicValues i:type="Program.DynamicSerializable">
<DynamicValue1 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st
ring" xmlns="">Value 1</DynamicValue1>
<DynamicValue2 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st
ring" xmlns="">Value 2</DynamicValue2>
</DynamicValues>
<Name>My Name</Name>
</Program.Root>