Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...