我正在尝试使用XmlReader
和关联的XmlReaderSettings
对象对某些文档执行XSD验证。我宣布一个ValidationEventHandler
,只要读者遇到验证问题,我就会调用它。但是当我尝试创建阅读器时,我得到XSDValidationException
。
知道会导致异常的原因吗?消息是:
System.Xml.Schema.XmlSchemaValidationException:未声明“http://www.w3.org/XML/1998/namespace:base”属性。
其中一个底层架构可能存在问题吗?
答案 0 :(得分:0)
验证您的实际XML文档在没有命名空间的情况下没有根元素。
当架构验证具有目标命名空间但正在验证的XML文档包含没有命名空间的任何根元素时,可能会出现此错误。
不幸的是,在这种情况下,模式验证只会生成警告,表明它找不到根元素的匹配模式,并且只有在设置了报告警告的特定标志时才会显示警告,这在使用验证时未设置XmlDocument的方法。
答案 1 :(得分:0)
在您的架构和文档中搜索xml:base
属性。如果存在,那么定义该属性的模式将需要在您的模式集中。
答案 2 :(得分:0)
代码示例可以很好地确定您正在做什么,但我可以做一些假设,因为我在同一个地方。我遇到了Using XSDs with includes,并根据我的意愿调整了接受的答案。
问题是XmlReader
似乎不知道所包含架构的基本路径是什么,如果你在Create()
XmlReader
时没有指定它。假设您有XML文件的文件路径,请使用XmlReader.Create(Stream input, XmlReaderSettings settings, String baseUri)
并提供XML文件的路径baseUri
。
示例:
using System.IO;
using System.Xml;
using System.Xml.Schema;
public void LoadXml(string path) {
XmlDocument doc = new XmlDocument();
XmlReader docReader;
XmlReaderSettings rdrOpts = new XmlReaderSettings();
rdrOpts.ValidationType = ValidationType.Schema;
rdrOpts.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation;
try {
// This line is what you're looking for:
docReader = XmlReader.Create(new FileStream(path, FileMode.Open, FileAccess.Read), rdrOpts, Path.GetDirectoryName(path));
doc.Load(docReader);
} catch (System.Xml.Schema.XmlSchemaValidationException ex) {
//...
} //and catch any other relevant exceptions here, like System.IO.FileNotFoundException
}