I am trying to delete just the XML element <Contact>
Where the ID matches the lstBox Selected Index. The code runs, however, it actually deletes everything inside my XML file, so I am left with an empty txt file. I have code like this:
private async void btnDeleteContact_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml");
XDocument xdoc = XDocument.Load(file.Path);
if (lstBox.SelectedIndex != -1)
{
xdoc.Element("Contacts")
.Elements("Contact")
.Where(x => (string)x.Attribute("ID") == lstBox.SelectedItem.ToString()).Remove();
lstBox.SelectedIndex = -1;
updateXMLFile(xdoc);
}
}
This is my XML file
<?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Contact>
<ID>salpea</ID>
<FirstName>Sally</FirstName>
<LastName>Pearson</LastName>
<Mobile>0431529562</Mobile>
<Email>sallyp@hotmail.com</Email>
</Contact>
<Contact>
<ID>gresul</ID>
<FirstName>Greg</FirstName>
<LastName>Sullivan</LastName>
<Mobile>0432928381</Mobile>
<Email>gregsul@outlook.com</Email>
</Contact>
<Contact>
<ID>chrmac</ID>
<FirstName>Christie</FirstName>
<LastName>Mack</LastName>
<Mobile>0421231231</Mobile>
<Email>christiemack@gmail.com</Email>
</Contact>
</Contacts>
The list box selection is in blue.
Not sure if it is relevant but this is my pastebin for the entire file here
Thanks for any help regarding the matter.