C# 在单一方法中针对 XSD 验证 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10025986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:10:40  来源:igfitidea点击:

Validate XML against XSD in a single method

c#xmlvalidationxsdschema

提问by Germstorm

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.

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

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

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.

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

if(!XmlManager.IsValidXml(
    @"ProjectTypes\ProjectType17.xml",
    @"Schemas\Project.xsd"))
{
     throw new XmlFormatException(
         string.Format(
             "Xml '{0}' is invalid.", 
             xmlFilePath));
}

采纳答案by psubsee2003

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

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

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/falsedepending on the situation.

如果传递 null 作为验证回调委托,大多数内置验证方法会在 XML 格式错误时抛出异常,因此您可以简单地捕获异常并根据情况返回true/ false

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;
}

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

想到的另一个选项突破了您的without using a callback标准的限制。您可以传递一个匿名方法并使用它来设置true/false返回值,而不是传递预定义的回调方法。

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;
}