假设我有一个模式,我希望输入文档符合该模式。我按照这样的架构加载文件:
// 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>
我想说的是,只有我有架构的名称空间应该通过架构验证。
答案 0 :(得分:2)
看起来很愚蠢,你想看的东西实际上在XmlReaderSettings
对象上:
settings.ValidationEventHandler +=
(node, e) => Console.WriteLine("Bad node: {0}", node);
答案 1 :(得分:1)
我最终解决的解决方案是基本上检查根节点是否在我期望的命名空间中。如果不是,那么我就像处理真正的架构验证失败一样对待它:
// Parse the bits we need out of that file
var rootNode = inputDoc.Root;
if (!rootNode.Name.NamespaceName.Equals(string.Empty, StringComparison.Ordinal))
{
throw new InvalidDataException(".abc file format namespace did not match.");
}
答案 2 :(得分:-1)