【问题标题】:How do I iterate through nodes within an XML XDocument, and if they meet a condition then delete them如何遍历 XML XDocument 中的节点,如果它们满足条件则删除它们
【发布时间】:2020-08-28 23:28:22
【问题描述】:

我正在寻找以下问题的指导。我正在尝试遍历父节点 id_Entries 中的所有节点,如下所示:

<id_Entries>
  <id_14222>"2020-01-21"</id_14222>
  <id_1451222>"2020-06-21"</id_1451222>
  <id_141222>"2018-06-21"</id_141222>
  <id_151222>"2019-06-21"</id_151222>
  <id_145122>"2021-06-21"</id_145122>
  <id_145222>"2020-04-21"</id_145222>
  <id_451222>"2020-01-21"</id_451222>
  <id_14512>"2020-02-21"</id_14512>
</id_Entries>

在循环中,我有几行代码获取日期和一个条件,如果当前日期长于一定数量,那么我将删除该子节点。

我遇到的问题是节点没有被删除。

这是我目前拥有的:

XDocument doc = XDocument.Load(filePath);

                foreach (var child in doc.Element("id_Entries").Elements())
                {
                    string entry = (string)child;
                    entry = entry.Substring(1, entry.Length - 2);
                    string[] splitDate = entry.Split('-');
                    DateTime entryDate = new DateTime(Int32.Parse(splitDate[0]), Int32.Parse(splitDate[1]), Int32.Parse(splitDate[2]));

                    int days = (currentDate - entryDate).Days;

                    if (days >= maxDays)
                        child.Remove();
                }

                StringBuilder builder = new StringBuilder();
                using (TextWriter writer = new StringWriter(builder))
                {
                    doc.Save(writer);
                }

通过研究,我了解到您无法在迭代期间删除节点。我不确定目前还有什么其他解决方案。

谢谢各位。

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    我找到了解决方案。遍历列表时,在末尾添加 .ToList() 。根据我的理解,我相信这将删除节点,因为我们目前没有遍历实际元素,因此能够删除列表中的当前节点。

    注意:这个解决方案很简单,这就是我实施它的原因。有更好的解决方案可以产生更好的运行时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      相关资源
      最近更新 更多