0

我使用 SDK 中的 xsd.exe 工具生成了基于 XSD 的 C# 类。然后我可以使用该类使用 XmlSerializer [反]序列化对象......但是序列化器似乎非常宽容。

如果缺少属性或“奇怪”的 XML 节点,我是否可以让序列化程序抛出异常?

我认为一种方法是修改属性的设置器并使其验证数据(或使用 XSD 验证)......但是对于这个问题还有其他替代解决方案吗?

4

1 回答 1

2

You can implement the IXmlSerializable interface and in the ReadXml method implementation, check for the specific elements that you require, throwing exceptions when you don't find them (or setting whatever notification you need to).

If you want to use a schema for validation (to use the minOccurs and maxOccurs schema attributes, for example), then you can configure the XmlReader instance to validate against the schema by setting the Schemas property on the XmlReaderSettings class that you pass to the Create method (note there are overloads of Create which take a TextReader, etc.).

于 2012-07-25T16:34:12.113 回答