因此,我尝试使用 XmlSchemaSet 针对 xsd 文件验证 xml 文件,并尝试在我的项目中实现以下解决方案,它找到了 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!";
}
有人看到我的问题吗?先感谢您!