c# - xmldocument 和嵌套模式

标签 c# .net schema xmldocument xmlschemaset

我正在使用 c# 和 .net 3.5 尝试根据包含的模式验证 xml 文档。

架构和包含如下

Schema1.xsd -> include another.xsd

another.xsd -> include base.xsd

当我尝试将 Schema1.xsd 添加到 XmlDocument 时,出现以下错误。

类型“YesNoType”未声明或不是简单类型。

我认为我收到此错误是因为当我加载 Schema1.xsd 架构时未包含 base.xsd 文件。

我尝试使用 XmlSchemaSet 类并将 XmlResolver uri 设置为模式的位置。

注意:所有模式都位于同一目录 E:\Dev\Main\XmlSchemas 下

这是代码

string schemaPath = "E:\\Dev\\Main\\XmlSchemas";

XmlDocument xmlDocSchema = new XmlDocument();

XmlSchemaSet s = new XmlSchemaSet();

XmlUrlResolver resolver = new XmlUrlResolver();

Uri baseUri = new Uri(schemaPath);

resolver.ResolveUri(null, schemaPath);

s.XmlResolver = resolver;

s.Add(null, XmlReader.Create(new System.IO.StreamReader(schemaPath + "\\Schema1.xsd"), new XmlReaderSettings { ValidationType = ValidationType.Schema, XmlResolver = resolver }, new Uri(schemaPath).ToString()));


xmlDocSchema.Schemas.Add(s);

ValidationEventHandler valEventHandler = new ValidationEventHandler
(ValidateNinoDobEvent);

try
{
xmlDocSchema.LoadXml(xml);
xmlDocSchema.Validate(valEventHandler);
}
catch (XmlSchemaValidationException xmlValidationError)
{
// need to interogate the Validation Exception, for possible further 
// processing.
string message = xmlValidationError.Message;
return false;
}

任何人都可以指出关于根据具有嵌套包含的模式验证 xmldocument 的正确方向。

最佳答案

我还有一个嵌套模式案例,我在验证时没有发现任何错误。我的代码看起来像下面这样。

private string strLogger = null;
    public bool ValidateXml(string path2XMLFile, string path2XSDFile)
    {
        bool isValidFile = false;
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, path2XSDFile);
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
            XmlReader reader = XmlReader.Create(path2XMLFile, settings);
            while (reader.Read()) ;
            if (String.IsNullOrEmpty(strLogger))
            {
                isValidFile = true;
            }                
        }
        catch (Exception ex)
        {
            LoggingHandler.Log(ex);
        }
        return isValidFile;
    }
    private void settings_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        strLogger += System.Environment.NewLine + "Validation Error Message  = [" + e.Message + "], " + "Validation Error Severity = [" + e.Severity + "], " + System.Environment.NewLine;
    } 

关于c# - xmldocument 和嵌套模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647921/

相关文章:

c# - 将 Lua 脚本加载到以文件名命名的表中

c# - 通过网络实例化游戏对象

c# - 在构建/保存和提交时设置 C# editorconfig 代码清理

c# - 断点会带来延迟吗?

json - Oracle PL/SQL 是否提供了 JSON 模式验证器?

xml - Base64 XML 二进制内容

c# - 获取呈现的 html 最终源

python - 使用扩展将字节添加到字节数组时为"unicode argument without an encoding"

c# - 在 C# .NET 中检查静态或动态 IP 地址?

java - 作为 XML 消息一部分的派生类型