我有在运行时读入的 xml 文件,是否可以在运行时针对 xsd 文件验证 xml?使用c#
I have xml files that I read in at runtime, is is possible to validate the xml against an xsd file at runtime? using c#
试试这个:
public void ValidateXmlDocument(
XmlReader documentToValidate, string schemaPath)
{
XmlSchema schema;
using (var schemaReader = XmlReader.Create(schemaPath))
{
schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
}
var schemas = new XmlSchemaSet();
schemas.Add(schema);
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemas;
settings.ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += ValidationEventHandler;
using (var validationReader = XmlReader.Create(documentToValidate, settings))
{
while (validationReader.Read())
{
}
}
}
private static void ValidationEventHandler(
object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
throw args.Exception;
}
Debug.WriteLine(args.Message);
}
这篇关于可以在运行时使用代码针对 xsd 验证 xml 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!