public static ValidationResult ValidateDocument(XmlDocument document, string schemaPath)
{
Contract.Requires<ArgumentNullException>(document != null);
Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(schemaPath));
ValidationResult result = new ValidationResult();
XmlSchemaSet schemaSet = null;
if (!string.IsNullOrWhiteSpace(schemaPath))
{
UrlResolver resolver = new UrlResolver();
XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(resolver);
XmlReader reader = XmlReader.Create(schemaPath, settings);
XmlSchema schema = XmlSchema.Read(reader, null);
schemaSet = new XmlSchemaSet { XmlResolver = resolver };
schemaSet.Add(schema);
schemaSet.Compile();
}
XDocument xdocument = XDocument.Parse(document.OuterXml, LoadOptions.SetLineInfo);
xdocument.Validate(schemaSet, (sender, args) =>
{
if (args.Severity == XmlSeverityType.Error)
{
result.Success = false;
var lineInfo = sender as IXmlLineInfo;
if (lineInfo != null)
{
result.Exception = new XmlException(args.Message, args.Exception, lineInfo.LineNumber, lineInfo.LinePosition);
}
else
{
result.Exception = args.Exception;
}
}
});
return result;
}