wis.niowy
wis.niowy

Reputation: 87

C#: delete an element from xml

I do writing to and reading from an xml file from C# WinFroms level. Additionally I want to have a function to delete an element with given content. My xml format:

<libraryImages>
    <imageLink>*link1*</imageLink>
    <imageLink>*link2*</imageLink>
</libraryImages>

Function body:

System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("XmlData.xml");
            xdoc.Root.Elements("imageLink").Select(el => el).Where(el => el.Value == pathToRemove).ToList().ForEach(el => el.Remove());

As a 'pathToRemove' parameter I pass link1 for example. The thing is - this doesn't remove this element from an xml - thus after I restart my application the content of my library is as previously, as if I hadn't removed any item. Why doesn't this work? I've browsed through many of stackoverflow questions, though I've found nothing.

Upvotes: 1

Views: 62

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You should update xml file after in-memory manipulations:

// read file from disc and build in-memory representation of xml
var xdoc = XDocument.Load("XmlData.xml");

// modify in-memory representation
xdoc.Root.Elements("imageLink").Where(el => el.Value == pathToRemove).Remove();

// save modified representation back to disck
xdoc.Save("XmlData.xml");

Upvotes: 2

Related Questions