为什么我的 xsd 没有在 C# 中自动引发必填字段异常

问题描述 投票:0回答:1
c# xml xsd-validation xmlreader
1个回答
0
投票

我稍微修改了您的代码,并注释掉/删除了

LogValidationError()
调用。

XSD 验证正在运行!请看下面。

我的猜测是问题正是与注释掉的

LogValidationError()
有关。

c#

void Main()
{   
    string xmlFilePath = @"e:\Temp\Zones.xml";
    string xsdFilePath = @"e:\Temp\Zones.xsd";
    
    ValidateXmlAgainstXsd(xmlFilePath, xsdFilePath);
}

private static bool ValidateXmlAgainstXsd(string xmlFilePath, string xsdFilePath)
{
    try
    {
        int numErreur = 0;
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add(null, xsdFilePath);
        schemaSet.Compile();



        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(schemaSet);
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags =
        XmlSchemaValidationFlags.ReportValidationWarnings |
        XmlSchemaValidationFlags.ProcessIdentityConstraints |
        XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationEventHandler += (sender, e) =>
        {
            //LogValidationError(xmlFilePath, e.Message, e.Exception, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, fileLogger, ref numErreur);
            Console.WriteLine(e.Message);
        };



        using (XmlReader reader = XmlReader.Create(xmlFilePath, settings))
        {
            while (reader.Read())
            {
                //process code
            }
        }
        return numErreur > 0 ? false : true;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error validating XML '{xmlFilePath}' against XSD '{xsdFilePath}': {ex.Message}");
        return false;
    }
}

输出

The required attribute 'logical' is missing.
The required attribute 'physical' is missing.
The required attribute 'is_city_saver' is missing.
The 'is_city_saver' attribute is invalid - The value 'Yes' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:boolean' - The string 'Yes' is not a valid Boolean value.
The 'logical' attribute is invalid - The value 'dt' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:unsignedByte' - The string 'dt' is not a valid Byte value.
© www.soinside.com 2019 - 2024. All rights reserved.