[英]Get the XML record number based on the error line number C#
下面是我的XML,我試圖根據發生錯誤的行號來獲取記錄/行號。 例如,如果驗證錯誤發生在第6行的值0.53處,我想知道它的記錄號為1,那么添加id="1", id="2"
..etc進行record
將是一個不錯的選擇,但根據我的要求,不能更改XML格式。
<?xml version='1.0' encoding='utf-8'?>
<records>
<record>
<date>2016-02-01</date>
<id>3</id>
<value>0.53</value>
<unit>mtrs</unit>
</record>
<record>
<date>2016-02-01</date>
<id>4</id>
<value>0.13</value>
<unit>mtrs</unit>
</record>
<record>
<date>2016-02-01</date>
<id>7</id>
<value>0.13</value>
<unit>mtrs</unit>
</record>
</records>
以下是我的代碼,我正在使用IXmlLineInfo
獲取錯誤行信息
//get the input file here
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
//sete the xsd schema path
string xsdPath = HttpContext.Current.Server.MapPath("~/XSD/MyFile.xsd");
//set the XSD schema here
var schema = new XmlSchemaSet();
schema.Add("", xsdPath);
var Message = "";
//validate the xml schema here
XDocument document = XDocument.Load(postedFile.InputStream, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo | LoadOptions.SetBaseUri);
//create a lists to add the error records
List<string> lstErrors = new List<string>();
document.Validate(schema, ValidationEventHandler);
//validate all the errors
document.Validate(schema, (sender, args) =>
{
IXmlLineInfo item = sender as IXmlLineInfo;
if (item != null && item.HasLineInfo())
{
//capture all the details needed here seperated by colons
Message = item.LineNumber + ";" +
(((System.Xml.Linq.XObject)item).Parent.Element("id")).Value + ";" +
((System.Xml.Linq.XElement)item).Name.LocalName + ";" +
args.Message + Environment.NewLine;
//add the error to a list
lstErrors.Add(Message);
}
});
}
請嘗試以下方法。
加載文檔后,在驗證之前,創建包含有關每個record
元素的索引和ID信息的字典。
XDocument document = XDocument.Load(...);
var dict = document.Root.Elements("record")
.Select((r, index) => new { r, index })
.ToDictionary(a => a.r, a => a.index);
然后在validate事件中使用此字典
if (item != null && item.HasLineInfo())
{
Message = dict[((XObject)item).Parent] + ";" +
item.LineNumber + ";" +
(((XObject)item).Parent.Element("id")).Value + ";" +
((XElement)item).Name.LocalName + ";" +
args.Message + Environment.NewLine;
lstErrors.Add(Message);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.