我可以失败,并在C#XmlSerializer的反序列化,如果没有找到一个元素? [英] Can I fail to deserialize with XmlSerializer in C# if an element is not found?

查看:395
本文介绍了我可以失败,并在C#XmlSerializer的反序列化,如果没有找到一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的XmlSerializer写在C#中读取对象到XML。我目前使用的属性的XmlElement XmlIgnore 来操作对象的序列化。

I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes XmlElement and XmlIgnore to manipulate the serialization of the object.

如果我的XML文件丢失,我需要一个XML元素,我的对象仍然反序列化(XML - >对象)就好了。我如何指示(最好是通过属性)某一个领域是必需的

If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably via Attributes) that a certain field is "required"?

下面是我使用目前的抽样方法:

Here is a sample method of what I am using currently:

[XmlElement(ElementName="numberOfWidgets")]
public int NumberThatIsRequired {
    set ...;
    get ...;
}



我的理想的解决方案是添加类似的 XmlRequired 属性。

此外,有没有什么属性了很好的参考可用来操纵XmlSerializer的行为?

Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?

推荐答案

我已经得到了第二部分的答案:的属性,控制XML序列化

I've got an answer for the second part: "Attributes that control XML serialization".

仍在调查第一部分...

Still investigating the first part...

编辑:我强烈怀疑你无法通过XML反序列化本身。我刚刚在一个示例架构,其中包括必要属性,运行XSD.EXE - 这也正是如果属性被标记为可选一样。如果有需要的属性的方式来设置的,我希望它在这种情况下实施。

I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case.

我怀疑你已经基本上得到了验证刚才您反序列化后的对象树。我们对此深感抱歉...

I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...

这篇关于我可以失败,并在C#XmlSerializer的反序列化,如果没有找到一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆