我正在使用 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 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!