Reputation: 343
How do I check for missing/skipped value in a particular nodes attribute value e.x.
<?xml version="1.0"?>
<root>
<lvl id="abc1">1036</lvl>
<lvl id="abc2">0036</lvl>
<lvl id="abc3">3.<dc>04</dc></lvl>
<lvl id="abc5">87.<dc>03</dc></lvl>
<lvl id="abc6">996</lvl>
<lvl id="abc10">203</lvl>
</root>
In the above xml the id attribute values abc4, abc7, abc8 and abc9 are missing..how do I check for these and get these values using linq to xml so that I can maybe write a log file or something say these values are missing, check the file?
I was thinking of using a helper method like
public static Boolean CompareNext(this XElement xe)
{
return Convert.ToInt16(xe.Attribute("id").Value.Replace("abc", ""))+1== Convert.ToInt16(xe.ElementsAfterSelf().FirstOrDefault().Attribute("rid").Value.Replace("ref", ""));
}
But struggling to implement it properly..
Upvotes: 0
Views: 105
Reputation: 11399
One possible solution is to extract the number of all ID's by replacing "abc"
:
//Load the document
XDocument doc = XDocument.Load(@"PATH_TO_FILE.xml");
//Extract all ID's
var ids = new List<int>();
foreach (var lvl in doc.Root.Elements())
{
if (int.TryParse(lvl.Attribute("id").Value.Replace("abc", ""), out int id))
{
ids.Add(id);
}
}
Based on the minimum and maximum it is possible to create a range of all expected ID's. Now you are able to get all missing ID's:
//Get the missing ID's
int minId = ids.Min();
int maxId = ids.Max();
var missingIds = Enumerable.Range(minId, maxId - minId).Except(ids);
Upvotes: 1