I use the following code to validate an XML file against an XSD file. It succesfully invokes the validation handler when errors are found and the value of xmlns in the XML file is valid. When it is invalid, the validation handler is not invoked.
private void ui_validate_Click(object sender, EventArgs e)
{
try
{
ui_output.Text = "";
XmlDocument xml_document = new XmlDocument();
xml_document.LoadXml(ui_XML.Text);
xml_document.Schemas.Add(null, XmlReader.Create(new System.IO.StringReader(ui_XSD.Text)));
xml_document.Validate(validation_handler);
}
catch (Exception ex)
{
ui_output.Text = "Exception: " + ex.Message;
}
}
private void validation_handler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
ui_output.Text += "Error: " + e.Message + Environment.NewLine;
break;
case XmlSeverityType.Warning:
ui_output.Text += "Warning: " + e.Message + Environment.NewLine;
break;
}
}
Update
An example for the accepted answer:
XmlDocument xml_document = new XmlDocument();
xml_document.Load(@"C:\temp\example.xml");
xml_document.Schemas.Add(null, @"C:\temp\example.xsd");
xml_document.Schemas.Compile();
XmlQualifiedName xml_qualified_name = new XmlQualifiedName(xml_document.DocumentElement.LocalName, xml_document.DocumentElement.NamespaceURI);
bool valid_root = xml_document.Schemas.GlobalElements.Contains(xml_qualified_name);
The way I handle this is to actually check first that for the Document Element (the root element) there is an XmlSchemaElement in your XmlReaderSettings.Schemas; if there isn’t, you can’t run the validation, which is why you get no error.
So, make sure that your XmlSchemaSet is compiled; then build an XmlQualifiedName using the LocalName and NamespaceUri; use that to lookup an XmlSchemaElement, using GlobalElements.
You should attempt to validate only if i) your schemas compile successfully and ii) you actually have a definition for the root element of the document.
Hope it helps…