I need to construct a set of dynamically created XML nodes from objects on the following format:
<Root>
<Name>My Name</Name>
<DynamicValues>
<DynamicValue1>Value 1</DynamicValue1>
<DynamicValue2>Value 2</DynamicValue2>
</DynamicValues>
</Root>
The name of the nodes within the DynamicValues
-tag are not known in advance. My initial thought was that this should be possible using an Expando Object, e.g:
[DataContract]
public class Root
{
[DataMember]
public string Name { get; set; }
[DataMember]
public dynamic DynamicValues { get; set; }
}
by initializing it with the values:
var root = new Root
{
Name = "My Name",
DynamicValues = new ExpandoObject()
};
root.DynamicValues.DynamicValue1 = "Value 1";
root.DynamicValues.DynamicValue2 = "Value 2";
and then Xml-serialize it:
string xmlString;
var serializer = new DataContractSerializer(root.GetType());
using (var backing = new StringWriter())
using (var writer = new XmlTextWriter(backing))
{
serializer.WriteObject(writer, root);
xmlString = backing.ToString();
}
However, when I run this, I get an SerializationException saying:
"Type 'System.Dynamic.ExpandoObject' with data contract name
'ArrayOfKeyValueOfstringanyType:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer."
Any ideas how I can achieve this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…