简体   繁体   English

如何通过索引从xml中删除元素

[英]how to remove elements from xml by index

I want to remove user-selected elements from an XML list, using element indexes. 我想使用元素索引从XML列表中删除用户选择的元素。 For example: 例如:

foreach (int index in indexes)
{
    Root.Descendants("book").ElementAt(index).Remove();
}

But this throws an IndexOutOfRangeException . 但这会引发IndexOutOfRangeException Any suggestions are appreciated. 任何建议表示赞赏。

As you remove items, the number of remaining "book" elements (and their indices) changes. 删除项目时,剩余的“ book”元素(及其索引)的数量会发生变化。 You might have 0, 1, 2, 3 in your indexes array, but once you remove the first item, your fourth index (3) is now out of range. 您的索引数组中可能有0、1、2、3,但是一旦删除了第一项,第四个索引(3)现在就超出了范围。 If you indices are consecutive, you can reverse the order in which you remove the elements, so the current index can never be "out of range." 如果索引是连续的,则可以颠倒删除元素的顺序,因此当前索引永远不会“超出范围”。

Try this: 尝试这个:

for (int i = indexes.Length - 1; i >= 0; i--)
{
    Root.Descendants("book").ElementAt(indexes[i]).Remove();
};

However, you mentioned that you want to remove "user-selected" elements, so I'm guessing your elements could be in a random order. 但是,您提到要删除“用户选择的”元素,因此我猜测您的元素可能是随机的。 Instead, you might want to try something like this: 相反,您可能想要尝试如下操作:

IEnumerable<XElement> books = Root.Descendants("book");
IList<XElement> booksToRemove = new List<XElement>(indexes.Length);

foreach (int index in indexes)
{
    booksToRemove.Add(books.ElementAt(index));
}

foreach (XElement book in booksToRemove)
{
    book.Remove();
}

Now you don't have to care what order the elements or the indexes are in before removing them. 现在,在删除元素或索引之前,不必关心它们的顺序。

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

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