Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

c# - Validate XML against XSD in a single method

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

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...