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

因此,我尝试使用XmlSchemaSet针对xsd文件验证xml文件,并尝试在我的项目中实现以下solution,它会找到xml文件中的所有错误,但它得到的行号始终是1由于某种原因。以下是处理该问题的代码:

xmlValidate类:

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

有人看到我的问题吗?预先谢谢你!

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

是否可以不格式化就加载XML? 尝试使用XmlDocument xml = new XmlDocument { PreserveWhitespace = true }

我想这对于获得正确的行号可能很重要,但我并没有坦白地说。

本文链接:https://www.f2er.com/3127447.html

大家都在问