简体   繁体   English

根据特定的XSD架构验证XML

[英]Validate an XML against a specific XSD schema

I have a webservice that gets specific XML which does not have a schema specified in the file itself. 我有一个获取特定XML的Web服务,该XML在文件本身中没有指定架构。 I do have XSD schemas in my project which will be used to test the obtained XML files against them. 我的项目中确实有XSD架构,该架构将用于根据它们测试获得的XML文件。

The problem is that whatever I do the validator seems to accept the files even when they aren't valid. 问题是,即使验证文件无效,我所做的验证程序似乎仍会接受它们。

The code I'm using is this (some parts omitted to make it easier): 我正在使用的代码是这样的(省略了一些部分以使其更容易):

var schemaReader = XmlReader.Create(new StringReader(xmlSchemeInput));
var xmlSchema = XmlSchema.Read(schemaReader, ValidationHandler);

var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.Schemas.Add(xmlSchema);
xmlReaderSettings.ValidationEventHandler += ValidationHandler;
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;

using(var xmlReader = XmlReader.Create(new StringReader(xmlInput), xmlReaderSettings))
{
    while (xmlReader.Read()) { }
}

// return if the xml is valid or not

I've found several solutions with an inline specified schema which work great, but with a schema specified like this (which I assume should work) I can't seem to find any. 我已经找到了一些使用内联指定架构的解决方案,这些解决方案效果很好,但是使用这样指定的架构(我认为应该可以正常工作),我似乎找不到任何解决方案。

Am I doing something wrong? 难道我做错了什么? Or am I just wrong in assuming this is how it should work? 还是我以为这是应该做的只是错了?

Thanks! 谢谢!

Try adding 尝试添加

xmlReaderSettings.Schemas.Compile()

after

xmlReaderSettings.Schemas.Add(xmlSchema);

worked for me in that situation. 在那种情况下为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM