Validate XML against XSD in a single method
c#, schema, validation, xml, xsd
Solution
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;
}
Problem
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)); } ```