简体   繁体   中英

Removing outdated elements from xml document using XML.Linq

I want to select the element with the latest timestamp (stored as an attribute) and delete any other that may exist (because that would mean the user messed with the xml file).

(directory, name and fileName are fields and/or parameters to the method containing this body)

        using ( FileStream fileStream = new FileStream( Path.Combine( directory, fileName ), FileMode.OpenOrCreate ) )
        {
            XElement xmlRoot = XElement.Load( fileStream );
            var query = from e in xmlRoot.Elements( "key" )
                where e.Attribute( "name" )?.Value == name
                orderby Int32.Parse(e.Attribute("timestamp")?.Value) descending select e;
            if(query.Count() == 1)
            {
                return query.First( );
            }
            else if (query.Count() > 1)
            {
                //here I need to delete any other than First (which has 
                //the latest timestamp, and return first, just like above)
            }
            else
            {

            }
        }

Specifically, I want to know how to delete any outdated Elements (those with a smaller timestamp) inside the if (query.Count() > 1) clause. LINQ has always been a bit misterious to me. Sorry if the question is trivial.

PS.: I encourage anyone who knows the specific computational name of this problem to edit and rename my question, and reword it as necessary. I'm an amateur.

You could do this using Remove extension method skipping the first element from your query result:

else if (query.Count() > 1)
 {
     var element=query.First();
     query.Skip(1).Remove();// do this to remove unwanted elements from your xml
     return element;       
 }

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