[英]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. 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: 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));
}
}
}
Main function:主要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!先感谢您!
Could it be, that you load your XML without formatting?可能是,您加载 XML 而不进行格式化? Try with XmlDocument xml = new XmlDocument { PreserveWhitespace = true }
尝试使用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.我想这对于获得正确的行号可能很重要,但老实说我没有检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.