use*_*702 2 .net xml xsd xml-namespaces
我使用以下代码针对XSD文件验证XML文件。发现错误并且xmlnsXML文件中的值有效时,它将成功调用验证处理程序。无效时,不会调用验证处理程序。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新 接受的答案的示例:
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);
Run Code Online (Sandbox Code Playgroud)
我处理此问题的方法是首先检查文档元素(根元素)是否在XmlReaderSettings.Schemas中有一个XmlSchemaElement ;如果没有,则无法运行验证,这就是为什么不会出现错误的原因。
因此,请确保您的XmlSchemaSet已编译;然后使用LocalName和NamespaceUri构建XmlQualifiedName;使用它使用GlobalElements查找XmlSchemaElement。
只有在i)模式编译成功和ii)实际上具有文档根元素的定义时,您才应尝试验证。
希望能帮助到你...
| 归档时间: |
|
| 查看次数: |
2139 次 |
| 最近记录: |