Rick1990
Rick1990

Reputation: 95

XML get deleted in C#

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>[email protected]</Email>
    </Contact>
    <Contact>
        <ID>gresul</ID>
        <FirstName>Greg</FirstName>
    <LastName>Sullivan</LastName>
        <Mobile>0432928381</Mobile>
        <Email>[email protected]</Email>
    </Contact>
    <Contact>
        <ID>chrmac</ID>
        <FirstName>Christie</FirstName>
    <LastName>Mack</LastName>
        <Mobile>0421231231</Mobile>
        <Email>[email protected]</Email>
    </Contact>
</Contacts>

The list box selection is in blue.

enter image description here

Not sure if it is relevant but this is my pastebin for the entire file here

Thanks for any help regarding the matter.

Upvotes: 0

Views: 124

Answers (3)

user8310908
user8310908

Reputation:

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)
        {
            var id = lstBox.SelectedItem.ToString();
            XmlNode node = xdoc.SelectSingleNode(string.Format("/Contacts/Contact[@ID='{0}']", id));

            if (node != null)
            {
                XmlNode parent = node.ParentNode;
                parent.RemoveChild(node);
                updateXMLFile(xdoc);
            }
        }
    }

Upvotes: 1

Rick1990
Rick1990

Reputation: 95

I took answers from all of you and this ended up working.

private async void updateXMLFile(XDocument xdoc)
        {
            try
            {
                //StorageFile file = await installedLocation.CreateFileAsync("Contacts.xml", CreationCollisionOption.ReplaceExisting);
                StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml"); //This line was the replacement for the one above.
                await FileIO.WriteTextAsync(file, xdoc.ToString());
            }
            catch (Exception ex)
            {
                String s = ex.ToString();
            }
        }

Also changed from x.Attribute to x.Element

thanks to all those who helped.

Upvotes: 1

Iswar
Iswar

Reputation: 2301

However, you can use xmlNode. I have gone through similar requirement and fixed by using xmlNode like this

 XmlTextReader reader = new XmlTextReader(path);

    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.ReadNode(reader);

    foreach (XmlNode chldNode in node.ChildNodes)
    {
        string employeeName = chldNode.Attributes["Name"].Value;
        if (employeeName == Employee)
        {                    
            //******your code here
        }
    }

Dummy XML

 <Root>
    <Employee Name ="TestName">
    <Childs/>
 </Root>

I have taken reference from here. In your context you can just delete the child node if matched.

hope it helps you.

Upvotes: 1

Related Questions