次のコードを使用して、XSDファイルに対してXMLファイルを検証します。エラーが検出され、XMLファイル内のxmlns
の値が有効な場合、検証ハンドラが正常に呼び出されます。無効な場合、検証ハンドラは呼び出されません。XmlDocument.Validateが無効な名前空間をチェックしない
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;
}
}
更新 受け入れ答えのための例:
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);