XML Serialize动态对象

我需要使用以下格式从对象构造一组动态创建的XML节点:

 My Name  Value 1 Value 2   

DynamicValues -tag中的节点名称不是事先知道的。 我最初的想法是,这应该可以使用Expando对象 ,例如:

 [DataContract] public class Root { [DataMember] public string Name { get; set; } [DataMember] public dynamic DynamicValues { get; set; } } 

通过使用值初始化它:

 var root = new Root { Name = "My Name", DynamicValues = new ExpandoObject() }; root.DynamicValues.DynamicValue1 = "Value 1"; root.DynamicValues.DynamicValue2 = "Value 2"; 

然后Xml-serialize它:

 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(); } 

但是,当我运行它时,我得到一个SerializationException说:

“类型’System.Dynamic.ExpandoObject’与数据契约名称’ArrayOfKeyValueOfstringanyType: http : //schemas.microsoft.com/2003/10/Serialization/Arrays ‘不是预期的。请考虑使用DataContractResolver或添加任何静态未知的类型已知类型的列表 – 例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

我有什么想法可以做到这一点?

 [Serializable] public class DynamicSerializable : DynamicObject, ISerializable { private readonly Dictionary dictionary = new Dictionary(); 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; } } 

输出:

   Value 1 Value 2  My Name  

在vb.net中尝试过但没有得到所需的输出。 需要帮忙。

_ Public Class DynamicSerializable Inherits System.Dynamic.DynamicObject实现ISerializable

 Private ReadOnly dict As New Dictionary(Of String, Object) Public Overrides Function TrySetMember(binder As SetMemberBinder, value As Object) As Boolean If Not dict.ContainsKey(binder.Name) Then dict.Add(binder.Name, value) Else dict(binder.Name) = value End If Return True End Function Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean Return dict.TryGetValue(binder.Name, result) End Function Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData For Each keyValPair In dict info.AddValue(keyValPair.Key, keyValPair.Value) Next End Sub 

结束类

使用的代码:

Dim root As New Root root.name =“1”root.DynamicValues = New DynamicSerializable

  root.DynamicValues.DynamicValue1 = "Value1" root.DynamicValues.DynamicValue2 = "Value1" Dim serializer = New DataContractSerializer(Root.GetType) Dim backing As New StringWriter Dim writer As New XmlTextWriter(backing) serializer.WriteObject(writer, Root) 

输出: