簡體   English   中英

在C#中使用xml驗證獲取行號

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM