简体   繁体   中英

Selecting XML Elements using Index

I have XML file in the following format;

<root>

<entry>
<details>
</entry>

<entry>
<details>
</entry>
...
</root>

I don't have any attributes and I display the details field in a ListBox control which allows copying and deleting items.

So, if the user deletes the second entry in the listbox, second entry in the xml file needs to be deleted completely.

Is there a way to do this ?

Currently, I'm using Linq-to-XML for writing the data.

EDIT: I forgot to mention the selection mode of the ListBox - it's MultiExtended.

Here's simple code to load, remove the indexed entry and then save the file.

XElement root = XElement.Load(file);
root.Elements("entry").ElementAt(index).Remove();
root.Save(file);

To match multiple:

int[] match = new int[] { 1, 10, 25, 33 };
var matches = root.Elements("entry").Where((x, i) => match.Contains(i));
foreach (var e in matches.ToList()) e.Remove();

It is a very loose definition, but the following ought to work:

// untested
var entries = xDoc.Root.Elements("entry").ToList();
entries[selectedIndex].Remove();
xDoc.Save(...);

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