我正在尝试做的是根据 XSD 验证 XML。这一切都非常简单,但我遇到了没有 namespace 的 XML 的问题。 如果命名空间与 XSD 的目标命名空间相匹配,C# 只会验证 xml。这似乎是正确的,但是没有 namespace 的 XML 或与 SchemaSet 不同的 XML 应该给出一个异常(exception)。是否有实现此目的的属性或设置?还是必须通过读取 xml 的 xmlns 属性手动获取命名空间?
一个例子来澄清:
代码:
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://example.com", @"test.xsd");
settings.Schemas.Add("http://example.com/v2", @"test2.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader r = XmlReader.Create(@"test.xml", settings);
XmlReader r = XmlReader.Create(new StringReader(xml), settings);
XmlDocument doc = new XmlDocument();
try
{
doc.Load(r);
}
catch (XmlSchemaValidationException ex)
{
Console.WriteLine(ex.Message);
}
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com" targetNamespace="http://example.com" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="test">
<xs:annotation>
<xs:documentation>Comment describing your root element</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+\.+[0-9]+" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>
有效的 XML:
<test xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</test>
无效的 XML,这不会验证:
<hello xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>
错误:“http://example.com:hello”元素未声明
。
无效的 XML,但会验证,因为命名空间不存在:
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>
我该如何解决这个问题?
非常感谢任何帮助。
最佳答案
xml 中的无效命名空间没有触发 XmlSchemaValidationException
的原因是,它只是一个警告。
因此,我们必须更改代码,以便也报告警告。
首先:在XmlReaderSettings
Validationflags
属性
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings;
PS:通过设置验证标志,确保你设置了所有需要的标志,否则一些验证检查将被跳过。
我正在使用 ProcessIdentityConstraints
,所以我的身份约束(xs:key, xs:keyref,...)也被验证了。更多信息,请访问 http://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschemavalidationflags.aspx .
Next:告诉验证器在报告警告时要做什么。创建一个 Validator 事件,当出现警告或错误时将触发该事件
private static void SchemaValidatorHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning || e.Severity == XmlSeverityType.Error)
{
//Handle your exception
}
}
最后:设置要用于验证的验证器事件处理程序
settings.ValidationEventHandler += new ValidationEventHandler(SchemaValidatorHandler);
就是这样
关于c# - .NET 中的 XML 验证和命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15428265/