简体   繁体   English

使用 XML.Linq 从 xml 文档中删除过时的元素

[英]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).我想选择具有最新时间戳(存储为属性)的元素并删除可能存在的任何其他元素(因为这意味着用户弄乱了 xml 文件)。

(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.具体来说,我想知道如何删除if (query.Count() > 1)子句中的任何过时元素(时间戳较小的元素if (query.Count() > 1) LINQ has always been a bit misterious to me. LINQ 对我来说一直有点神秘。 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. PS.:我鼓励任何知道这个问题的具体计算名称的人编辑和重命名我的问题,并根据需要对其进行改写。 I'm an amateur.我是业余爱好者。

You could do this using Remove extension method skipping the first element from your query result:您可以使用Remove扩展方法跳过查询结果中的第一个元素来执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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