XmlSerializer 和可接受的值
您好,我正在开发一个项目,在该项目中我应该将对象序列化和反序列化为 Xml,然后返回对象。我使用 XmlSerializer 类来实现此目的。所以我的问题是,如果元素的属性值无效,我无法弄清楚如何阻止序列化。例如,我有一个名为 person 的元素,其中包含 1 个属性(名称) 我想阻止用户在此属性中输入除(Alex,Nick,..)以外的其他名称,在本例中我需要类似 xsd 限制(模式)的内容,但对于我的模型。我该如何解决这个问题?
Hello I am working on an project in which I should serialize and deserialize my objects to Xml and back to objects. I use the XmlSerializer class in order to achieve this. So my problem is that I can't figure out how to prevent the serialization if the attribute value of an element is invalid. For example I have an element with name person which contain 1 attribute (name)
I would like to prevent the user to put other names than (Alex, Nick,..) in this attribute I need something like xsd restriction (pattern) in this case but for my model. How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只需要条件序列化,可以使用 ShouldSerialize* 模式来完成此操作。因此,如果您有一个属性
Name
(例如),您可以添加:该方法需要对于 XmlSerializer 来说是公共的,尽管相同的模式可以在其他地方(例如 System.ComponentModel)工作,即使不公开。
If you just want conditional serialisation, you can do this with the ShouldSerialize* pattern. So if you have a property
Name
(for example), you can add:The method needs to be public for XmlSerializer, although the same pattern works in other places (System.ComponentModel, for example) even if no-public.
我不确定在某些情况下忽略某些数据是否是个好主意,但如果您确实想这样做,请查看 IXmlSerialized 接口。我认为手动实现这个接口将是满足您的要求的唯一方法。
I'm not sure weather it is a good idea to ignore some data in certain circumstances, but if you really wanna do this, take a look at the IXmlSerializable Interface. I think implementing this interface manually will be the only way to fulfill your requirements.