简体   繁体   中英

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. I've gotten to the stage of making a button that deletes a the xml element from a file based on where it is. 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> ". 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 ".

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..

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