[英]Get line number with xml validation in C#
我有一个需要验证的xml文件。 我为行号添加了一个名为“ Ln”的标签。 当出现验证错误作为错误列表的一部分时,我试图返回此行号。 这是我的xml:
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName><Ln>0</Ln>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName><Ln>1</Ln>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName><Ln>2</Ln>
</employee>
</employees>
我使用以下代码对其进行验证:
System.Xml.Schema.XmlSchemaSet schemas = new System.Xml.Schema.XmlSchemaSet();
schemas.Add("", @"Path to xsd");
Console.WriteLine("Attempting to validate");
XDocument UsrDoc = XDocument.Load(@"My xml file");
bool errors = false;
UsrDoc.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
});
Console.WriteLine("UsrDoc {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
我想将错误列表作为字符串列表返回,最重要的是包括行号。 到目前为止,我还没有弄清楚如何做。
任何帮助将不胜感激。
乙
我使用XmlReader
进行验证
using (var stream = new FileStream("My xml file", FileMode.Open))
{
var isErrorOccurred = false;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add("", "my schema");
settings.ValidationEventHandler += (sender, args) =>
{
isErrorOccurred = true;
Console.WriteLine("{0}", args.Exception.LineNumber);;
};
stream.Seek(0, SeekOrigin.Begin);
XmlReader reader = XmlReader.Create(stream, settings);
// Parse the file.
while (reader.Read())
{}
if (isErrorOccurred)
// do something
}
ValidationEventArgs中的XmlSchemaException具有LineNumber。 参见: https : //msdn.microsoft.com/de-de/library/system.xml.schema.xmlschemaexception(v=vs.110).aspx
在您的代码中:
UsrDoc.Validate(schemas, (o, e) =>
{
Console.WriteLine("Line {0}: {1}", e.Exception.LineNumber, e.Message);
errors = true;
});
还有其他有用的信息,例如LinePosition等。
编辑:我刚刚读到您想要一个字符串列表:在这种情况下,您必须在事件处理程序中构建此列表,或者将所需的信息传递给另一个方法。 但是,我不确定在第一个错误之后验证过程是否继续? 也许您必须设置特定的设置以使其运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.