Search code examples
c#xmlxsdxsd-validationxmlschemaset

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


So I am trying to validate a xml file against a xsd file using XmlSchemaSet and I tried implementing the following solution in my project and it finds all the errors in the xml file but the line number it gets is always 1 for some reason. Here is the code that deals with the issue:

xmlValidate 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));
        }
    }
}

Main function:

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!"; 
   }

Does anyone see my issue? Thank you in advance!


Solution

  • Could it be, that you load your XML without formatting? Try with XmlDocument xml = new XmlDocument { PreserveWhitespace = true }

    I guess that could be important for getting the right line number but I did not check to be honest.