以下代码可帮助我验证带有XSD架构的XML文件。
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, xsdFilePath);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(settings_ValidationEventHandler);
XmlDocument document = new XmlDocument();
document.Load(xmlFilePath);
XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
while (rdr.Read())
{
}
isValid = true;
ValidationEventHandler还告诉我错误是什么,但没有告诉我他们所在的“哪里”或“在哪一行”。有没有办法获得XML无法验证的行号?
答案 0 :(得分:28)
这不会影响你的目标吗?
创建一个
XmlReaderSettings
对象并通过该对象启用警告。很遗憾,似乎无法将您自己的
XmlReaderSettings
对象传递给XmlDocument.Validate()
相反,您可以使用验证XmlReader
和XmlNodeReader
来验证现有XmlDocument
(XmlNodeReader
使用StringReader
而不是XmlDocument
)
XmlDocument x = new XmlDocument();
x.LoadXml(XmlSource);
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += Handler;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, ExtendedTreeViewSchema);
settings.ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation ;
StringReader r = new StringReader(XmlSource);
using (XmlReader validatingReader = XmlReader.Create(r, settings)) {
while (validatingReader.Read()) { /* just loop through document */ }
}
处理程序:
private static void Handler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
System.Diagnostics.Trace.WriteLine(
String.Format("Line: {0}, Position: {1} \"{2}\"",
e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
}
答案 1 :(得分:3)
ValidationEventArgs.Message在其文本中包含行/列。
ValidationEventArgs.Exception包含line和column的字段。