当我只知道祖先类的类型时,如何反序列化 XML?
假设我想反序列化它(我已经删除了命名空间以使事情变得更简单):
<TextField>
<Caption>Location</Caption>
<Name>Location</Name>
</TextField>
TextField 继承自 FormField,因此在我的 FormField 类定义中看起来像这样:
[KnownType(typeof(TextField))]
[DataContract(Name = "FormField"]
public abstract class FormField
{
[DataMember]
public string Name { get; set; }
}
TextField 类看起来像这样:
[DataContract(Name = "TextField")]
public class TextField : FormField
{
[DataMember]
public string Caption { get; set; }
}
我尝试使用这个进行反序列化:
internal static FormField Deserialize(string xml)
{
var serializer = new DataContractSerializer(typeof(FormField)});
using (var backing = new StringReader(xml))
{
using (var reader = new XmlTextReader(backing))
{
return serializer.ReadObject(reader) as FormField;
}
}
}
I得到 SerializationException:“期望元素‘FormField’...”
Let's assume I want to deserialize this (I've removed the namespaces to make things simpler):
<TextField>
<Caption>Location</Caption>
<Name>Location</Name>
</TextField>
TextField inherits from FormField, so in my class definition of FormField looks something like this:
[KnownType(typeof(TextField))]
[DataContract(Name = "FormField"]
public abstract class FormField
{
[DataMember]
public string Name { get; set; }
}
TextField class looks like this:
[DataContract(Name = "TextField")]
public class TextField : FormField
{
[DataMember]
public string Caption { get; set; }
}
I tried deserializing using this:
internal static FormField Deserialize(string xml)
{
var serializer = new DataContractSerializer(typeof(FormField)});
using (var backing = new StringReader(xml))
{
using (var reader = new XmlTextReader(backing))
{
return serializer.ReadObject(reader) as FormField;
}
}
}
I get a SerializationException: "Expecting element 'FormField'..."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么你的模型不应该是这样的吗?
只是一次尝试,实际上我刚刚开始深入研究 DataContractSerializer 内容列表之夜,这很奇怪。
Shouldn't your model look like this then?
just a stab, I actually just started diving into the DataContractSerializer stuff list night oddly enough.
为了解决我的问题,我向 XML 添加了一个容器节点,使其看起来像这样:
我创建了这个类:
我的反序列化方法看起来像这样:
如果有人有更好的解决方案,请分享:)
To solve my problem I added a container node to the XML, so that it looks like this:
I created this class:
And my deserialize method looks like this:
If anyone has a better solution, please share it :)