简体   繁体   English

在C#中使用xml验证获取行号

[英]Get line number with xml validation in C#

I have an xml file that i need to validate. 我有一个需要验证的xml文件。 I have added a tag called "Ln" for line number. 我为行号添加了一个名为“ Ln”的标签。 I'm trying to return this line number when there is a validation error as part of the error list. 当出现验证错误作为错误列表的一部分时,我试图返回此行号。 Here is my xml: 这是我的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>

I use the following code to validate it: 我使用以下代码对其进行验证:

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();

I would like to return the error list as a list of strings and most importantly include the line number. 我想将错误列表作为字符串列表返回,最重要的是包括行号。 I have failed so far to figure out how. 到目前为止,我还没有弄清楚如何做。

Any help will be highly appreciated. 任何帮助将不胜感激。

B

I used a XmlReader to validate 我使用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
}

The XmlSchemaException from the ValidationEventArgs has the LineNumber. ValidationEventArgs中的XmlSchemaException具有LineNumber。 see: https://msdn.microsoft.com/de-de/library/system.xml.schema.xmlschemaexception(v=vs.110).aspx 参见: https : //msdn.microsoft.com/de-de/library/system.xml.schema.xmlschemaexception(v=vs.110).aspx

in your code: 在您的代码中:

    UsrDoc.Validate(schemas, (o, e) =>
    {
      Console.WriteLine("Line {0}: {1}", e.Exception.LineNumber, e.Message);
      errors = true;
    });

There are also other useful informations, such as LinePosition and so on. 还有其他有用的信息,例如LinePosition等。

EDIT: I just read that you want a list of strings: In this case you have to build this list in the event handler or pass the information you need to another method. 编辑:我刚刚读到您想要一个字符串列表:在这种情况下,您必须在事件处理程序中构建此列表,或者将所需的信息传递给另一个方法。 However, i am not sure if the validation process continues after the first error? 但是,我不确定在第一个错误之后验证过程是否继续? Maybe you have to set specific settings to keep it running. 也许您必须设置特定的设置以使其运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM