c# - C# - 使用 XmlSchemaSet 验证 XML 时如何在错误消息中获取正确的行号?
问题描述
因此,我尝试使用 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!";
}
有人看到我的问题吗?先感谢您!
解决方案
会不会是您在没有格式化的情况下加载您的 XML?尝试XmlDocument xml = new XmlDocument { PreserveWhitespace = true }
我想这对于获得正确的行号可能很重要,但老实说我没有检查。
推荐阅读
- java - 如果应该在实现它的子类中定义接口,接口有什么用
- python - 导航工具栏未显示在窗口中
- react-native - iOS 上“expo-localization”的 React-Native 问题
- python - 如何在python中编写一个单词搜索程序?
- jenkins - Jenkins 与 GitHub 和 Ionic 项目集成的问题
- oauth-2.0 - 将 mautic 服务器与另一个 java 应用程序集成
- sql - SQL求和多个字段的条件
- node.js - 在 mqtt.js 中发布无法访问的主题时如何捕获“访问错误”?
- mysql - 连接被拒绝 SQL
- android - 如何在不同的 Fragment 上使用 ModelView 来获取 EditText 的输入并将 TextView 设置为其值?