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(
@"ProjectTypes\ProjectType17.xml",
@"Schemas\Project.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.
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.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 atrue/falsereturn value.