简体   繁体   中英

Querying an XML log with LINQ

I am logging all changes to a folder with with FileWatcher to an XML file with

XDocument log = XDocument.Load(logpath);
XElement change = new XElement("change");
change.Add(new XAttribute("datetime", stamp));
change.Add(new XAttribute("status", "Deleted"));
change.Add(new XAttribute("filename", filepath));


log.Add(change);
log.Save(logpath);

Then, when I want to look at the changes made by a certain timestamp, I query it with

var query = _filelog.Elements().Where(x => ((DateTime)x.Element("datetime")) <= time);

Which is just an IEnumerable of XElements and not very convenient to work with. How can I turn it into a more convenient collection such as list of dictionaries of keyvaluepairs status : "deleted" etc? There is a different amount of XAttributes in the XElements depending on the type of change.

Additionally, is there a way to query a last change for every filename until the timestamp rather than every change up to and including that point?

Try one of solutions below. First is if DateTime is unique, second is if there are duplicate DateTime values.

            Dictionary<DateTime, XElement> dict1 = doc.Elements("change")
                .GroupBy(x => DateTime.Parse(x.Attribute("datetime").Value), y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            Dictionary<DateTime, List<XElement>> dict2 = doc.Elements("change")
                .GroupBy(x => DateTime.Parse(x.Attribute("datetime").Value), y => y)
                .ToDictionary(x => x.Key, y => y.ToList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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