假设我有一个模式,我希望输入文档符合该模式。我根据这样的架构加载文件:
// Load the ABC XSD
var schemata = new XmlSchemaSet();
string abcSchema = FooResources.AbcTemplate;
using (var reader = new StringReader(abcSchema))
using (var schemaReader = XmlReader.Create(reader))
{
schemata.Add(string.Empty, schemaReader);
}
// Load the ABC file itself
var settings = new XmlReaderSettings
{
CheckCharacters = true,
CloseInput = false,
ConformanceLevel = ConformanceLevel.Document,
IgnoreComments = true,
Schemas = schemata,
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
};
XDocument inputDoc;
try
{
using (var docReader = XmlReader.Create(configurationFile, settings))
{
inputDoc = XDocument.Load(docReader);
}
}
catch (XmlSchemaException xsdViolation)
{
throw new InvalidDataException(".abc file format constraint violated.", xsdViolation);
}
这可以很好地检测文件中的琐碎错误。然而,因为模式被锁定到一个命名空间,像下面这样的文档是无效的,但会偷偷溜过去:
<badDoc xmlns="http://Foo/Bar/Bax">
This is not a valid document; but Schema doesn't catch it
because of that xmlns in the badDoc element.
</badDoc>
我想说只有我拥有架构的命名空间才能通过架构验证。