简体   繁体   English

在C#中使用xsd验证xml文件。它实际验证多少?

[英]validate xml file using xsd in C#.. How much does it actually validate?

Have have been trying to make a validator for my xml files. 一直在尝试为我的xml文件创建一个验证器。 I have used some of the other examples that can be found on this site (like How to validate an XML document? ). 我使用了在此站点上可以找到的其他一些示例(例如, 如何验证XML文档? )。

I just don't see it working the way I expect. 我只是没有看到它按我期望的方式工作。 What does actually get validated? 实际验证了什么?

Almost no matter what I change in the xml file, the validator dosent sees it as an error. 几乎无论我在xml文件中进行什么更改,验证器剂量器都将其视为错误。 I thought the validator would see if the xml file contains an element not defined in the xsd. 我以为验证器将查看xml文件是否包含xsd中未定义的元素。 The validator only catches normal xml syntax errors. 验证器仅捕获正常的xml语法错误。

So whats the point of using the xsd if it doesn't have an influence? 那么,如果没有影响,使用xsd有什么意义呢?

My validator 我的验证人

string xsd_file = "Message.xsd";
XmlSchema xsd = new XmlSchema();
xsd.SourceUri = xsd_file;

XmlSchemaSet ss = new XmlSchemaSet();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
ss.Add(null, xsd_file);
if (ss.Count > 0)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(ss);
    settings.Schemas.Compile();
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
    XmlTextReader r = new XmlTextReader(filepath);
    using (XmlReader reader = XmlReader.Create(r, settings))
    {
        try
        {
            while (reader.Read())
            {
            }
        }
        catch (XmlException ex)
        {

            throw;
        }                        
    }
}

The code for the validation eventhandler is missing. 验证事件处理程序的代码丢失。

Looking at my working code which is slightly different I have this 看我的工作代码有一点不同我有这个

settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationFlags;

Can't remember why I had to add it though. 忘记了为什么我必须添加它。

First thing to do is make sure the eventhandler is getting triggered, after that it may be a problem with your xsd. 首先要做的是确保触发了事件处理程序,之后这可能是xsd的问题。

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

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