因此,我尝试使用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!";
}
有人看到我的问题吗?预先谢谢你!