简体   繁体   English

使用索引选择XML元素

[英]Selecting XML Elements using Index

I have XML file in the following format; 我有以下格式的XML文件;

<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. 我没有任何属性,并且在允许复制和删除项目的ListBox控件中显示详细信息字段。

So, if the user deletes the second entry in the listbox, second entry in the xml file needs to be deleted completely. 因此,如果用户删除列表框中的第二个条目,则需要完全删除xml文件中的第二个条目。

Is there a way to do this ? 有没有办法做到这一点 ?

Currently, I'm using Linq-to-XML for writing the data. 目前,我正在使用Linq-to-XML编写数据。

EDIT: I forgot to mention the selection mode of the ListBox - it's MultiExtended. 编辑:我忘了提到列表框的选择模式-它是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(...);

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

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