可以在运行时使用代码针对 xsd 验证 xml 吗? [英] Possible to validate xml against xsd using code at runtime?

查看:13
本文介绍了可以在运行时使用代码针对 xsd 验证 xml 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在运行时读入的 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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆