XML 序列化动态对象
我需要根据以下格式的对象构造一组动态创建的 XML 节点:
<Root>
<Name>My Name</Name>
<DynamicValues>
<DynamicValue1>Value 1</DynamicValue1>
<DynamicValue2>Value 2</DynamicValue2>
</DynamicValues>
</Root>
DynamicValues
标记内的节点名称事先未知。我最初的想法是,这应该可以使用 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 序列化:
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< /a>' 预计不会。考虑使用 DataContractResolver 或添加任何 已知类型列表中静态未知的类型 - 例如, 通过使用 KnownTypeAttribute 属性或将它们添加到 传递给 DataContractSerializer 的已知类型列表。”
我有什么想法可以实现这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输出:
Output: