通过单一方法针对 XSD 验证 XML [英] Validate XML against XSD in a single method

查看:22
本文介绍了通过单一方法针对 XSD 验证 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个 C# 方法,该方法需要针对外部 XSD 验证 XML 并返回一个布尔结果,指示它是否格式正确.

I need to implement a C# method that needs to validate an XML against an external XSD and return a Boolean result indicating whether it was well formed or not.

public static bool IsValidXml(string xmlFilePath, string xsdFilePath);

我知道如何使用回调进行验证.我想知道它是否可以在一个方法中完成,而不使用回调.我需要这个纯粹是为了美观:我需要验证多达几十种类型的 XML 文档,所以我想做如下简单的事情.

I know how to validate using a callback. I would like to know if it can be done in a single method, without using a callback. I need this purely for cosmetic purposes: I need to validate up to a few dozen types of XML documents so I would like to make is something as simple as below.

if(!XmlManager.IsValidXml(
    @"ProjectTypesProjectType17.xml",
    @"SchemasProject.xsd"))
{
     throw new XmlFormatException(
         string.Format(
             "Xml '{0}' is invalid.", 
             xmlFilePath));
}

推荐答案

根据您是否要对非异常事件使用异常,我可以想到几个选项.

There are a couple of options I can think of depending on whether or not you want to use exceptions for non-exceptional events.

如果你传递一个 null 作为验证回调委托,如果 XML 格式错误,大多数内置验证方法都会抛出异常,因此你可以简单地捕获异常并返回 true/false视情况而定.

If you pass a null as the validation callback delegate, most of the built-in validation methods will throw an exception if the XML is badly formed, so you can simply catch the exception and return true/false depending on the situation.

public static bool IsValidXml(string xmlFilePath, string xsdFilePath, XNamespace namespaceName)
{
    var xdoc = XDocument.Load(xmlFilePath);
    var schemas = new XmlSchemaSet();
    schemas.Add(namespaceName, xsdFilePath);

    try
    {
        xdoc.Validate(schemas, null);
    }
    catch (XmlSchemaValidationException)
    {
        return false;
    }

    return true;
}

想到的另一个选项是在不使用回调 标准的情况下突破的限制.除了传递预定义的回调方法,您还可以传递一个匿名方法并使用它来设置 true/false 返回值.

The other option that comes to mind pushes the limits of your without using a callback criterion. Instead of passing a pre-defined callback method, you could instead pass an anonymous method and use it to set a true/false return value.

public static bool IsValidXml(string xmlFilePath, string xsdFilePath, XNamespace namespaceName)
{
    var xdoc = XDocument.Load(xmlFilePath);
    var schemas = new XmlSchemaSet();
    schemas.Add(namespaceName, xsdFilePath);

    Boolean result = true;
    xdoc.Validate(schemas, (sender, e) =>
         {
             result = false;
         });

    return result;
}

这篇关于通过单一方法针对 XSD 验证 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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