简体   繁体   English

为什么我的代码不会删除 XML 文件中的特定元素

[英]Why won't my code delete the specific element in a XML file

So to learn c# I have been creating a program that diplays stuff I need to renember and give me the ability to change and delete those.因此,为了学习 c#,我一直在创建一个程序来显示我需要记住的内容,并让我能够更改和删除这些内容。 I've gotten to the stage of making a button that deletes a the xml element from a file based on where it is.我已经到了制作一个按钮的阶段,该按钮根据文件的位置从文件中删除 xml 元素。 The problem is that only the first button deletes anything and it deletes everything.问题是只有第一个按钮会删除任何东西,它会删除所有东西。 I was wondering what I did wrong.我想知道我做错了什么。 Can anyone help please?有人可以帮忙吗?

Sorry that it's messy.对不起,它很乱。

String Buttonname = (sender as Button).Name;
int RowCount = Int16.Parse(Buttonname.Remove(0, 9));

string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dataPath = Path.Combine(appDataPath, "Remembrall 2.0");
string EventslistFullPath = Path.Combine(dataPath, "Events.xml");

Label Labelname = (Label)this.Controls.Find("DetailsLbl"+RowCount, true)[0];
string Detailtext = Labelname.Text;
//gets the text from a dynamicaly generated textbox

MessageBox.Show (Detailtext);

for (int z = 0; z < Table.ColumnCount; z++)
{
    Control con = Table.GetControlFromPosition(z, RowCount);
    Table.Controls.Remove(con);
    con.Dispose();
}

XDocument EventDoc = XDocument.Load(EventslistFullPath);

label1.Text = Detailtext;

EventDoc.Descendants("Events").Where(ele => ele.Element("Event").Value == Detailtext).Remove();
//Deletes the element based off the value of the text.


EventDoc.Save(EventslistFullPath); 

The line线路

EventDoc.Descendants("Events").Where(ele => ele.Element("Event").Value == Detailtext).Remove();

says "find all <Events> nodes under the event doc; for each, see if the first <Event> node in there matches Detailtext ; if it does, remove that <Events> ".说“在事件文档下找到所有<Events>节点;对于每个节点,查看其中的第一个<Event>节点是否与Detailtext匹配;如果匹配,则删除该<Events> ”。 You probably meant:你的意思可能是:

EventDoc.Descendants("Events").Elements("Event").Where(evt => evt.Value == Detailtext).Remove();

which says "find all <Events> nodes, and for each find all the <Event> nodes under it; remove any of those <Event> that match Detailtext ".它说“找到所有<Events>节点,并为每个节点找到它下面的所有<Event>节点;删除任何与Detailtext匹配的<Event> ”。

Note that this still means that duplicates get a little dicey, ie if multiple nodes have the value "abc" , clicking delete on any one of the "abc" will remove all of them..请注意,这仍然意味着重复项有点冒险,即如果多个节点具有值"abc" ,单击删除任何一个"abc"将删除所有这些..

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

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