xmlserializer validation(xmlserializer 验证)
问题描述
我正在使用 XmlSerializer 反序列化 Xml 档案.但我发现生成的类 xsd.exe 只提供读取 xml 的能力,但没有验证.例如,如果文档中缺少一个节点,则生成的类的属性字段将为空,而不是像我预期的那样抛出验证异常.我怎样才能做到这一点?谢谢!
I'm using XmlSerializer to deserialize Xml achives. But I found the class xsd.exe generated only offers capability to read the xml, but no validation. For example, if one node is missing in a document, the attribute field of the generated class will be null, rather than throws a validation exception as I expected. How can I achieve that? Thanks!
推荐答案
以下代码应在反序列化时针对架构进行验证.类似的代码可用于在序列化时针对模式进行验证.
The following code should validate against a schema while deserializing. Similar code can be used to validate against a schema while serializing.
private static Response DeserializeAndValidate(string tempFileName)
{
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(LoadSchema());
Exception firstException = null;
var settings = new XmlReaderSettings
{
Schemas = schemas,
ValidationType = ValidationType.Schema,
ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler +=
delegate(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
Console.WriteLine(args.Message);
}
else
{
if (firstException == null)
{
firstException = args.Exception;
}
Console.WriteLine(args.Exception.ToString());
}
};
Response result;
using (var input = new StreamReader(tempFileName))
{
using (XmlReader reader = XmlReader.Create(input, settings))
{
XmlSerializer ser = new XmlSerializer(typeof (Response));
result = (Response) ser.Deserialize(reader);
}
}
if (firstException != null)
{
throw firstException;
}
return result;
}
这篇关于xmlserializer 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:xmlserializer 验证
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01