C# - 如何在使用 XmlSchemaSet 验证 XML 时在错误消息中获取正确的行号?

C# - How to get the right line number in error message when validating XML using XmlSchemaSet?

所以我尝试使用 XmlSchemaSet 对照 xsd 文件验证 xml 文件,我尝试在我的项目中实现以下 solution,它发现了xml 文件,但由于某种原因,它获取的行号始终为 1。这是处理该问题的代码:

xml验证 class:

public class xmlValidate
{
    private IList<string> allValidationErrors = new List<string>();

    public IList<string> AllValidationErrors
    {
        get
        {
            return this.allValidationErrors;
        }
    }

    public void checkForErrors(object sender, ValidationEventArgs error)
    {
        if (error.Severity == XmlSeverityType.Error || error.Severity == XmlSeverityType.Warning)
        {
            this.allValidationErrors.Add(String.Format("<br/>" + "Line: {0}: {1}", error.Exception.LineNumber, error.Exception.Message));
        }
    }
}

主要功能:

public string validate(string xmlUrl, string xsdUrl)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(xmlUrl);
        xml.Schemas.Add(null, xsdUrl);

        string xmlString = xml.OuterXml;
        XmlSchemaSet xmlSchema = new XmlSchemaSet();
        xmlSchema.Add(null, xsdUrl); 

        if (xmlSchema == null)
        {
            return "No Schema found at the given url."; 
        }

        string errors = "";
        xmlValidate handler = new xmlValidate();
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.CloseInput = true;
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(handler.checkForErrors);
        settings.Schemas.Add(xmlSchema);
        settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema 
                                 | XmlSchemaValidationFlags.ProcessSchemaLocation 
                                 | XmlSchemaValidationFlags.ReportValidationWarnings 
                                 | XmlSchemaValidationFlags.ProcessIdentityConstraints;
        StringReader sr = new StringReader(xmlString); 

        using (XmlReader vr = XmlReader.Create(sr, settings))
        {
            while (vr.Read()) { }
        }

        if (handler.AllValidationErrors.Count > 0)
        {
            foreach (String errorMessage in handler.AllValidationErrors)
            {
                errors += errorMessage; 
            }
            return errors; 
        }

        return "No Errors!"; 
   }

有人看到我的问题了吗?提前致谢!

莫非,您加载 XML 时没有格式化? 试试 XmlDocument xml = new XmlDocument { PreserveWhitespace = true }

我想这对于获得正确的行号可能很重要,但老实说我没有检查。