How to remove an element from an xml using Xdocument when we have multiple elements with same name but different attributes

naren.katneni picture naren.katneni · Dec 5, 2012 · Viewed 27.2k times · Source

I have an xml document which looks like this:

<Applications>
  <myApp>
    <add key="ErrorDestinationEventLog" value="EventLog" />
    <add key="version" value="5.0.0.0" />
    <add key="DebugMode_RUN" value="true" />
  </myApp>
</Applications>

All the elements have same element name but different attributes. How do I remove one particular element and it's attributes from this xml using XDocument in C#?

xd.Element("Applications").Element("myApp").Element(xe.Name).RemoveAll();

The above command is not working as all the elements have same name.

Is there any way to identify an element with, other than it's name? And if so, how can I use this to remove it from the XDocument?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Dec 5, 2012
string key = "version";
XDocument xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("add")
    .Where(x => (string)x.Attribute("key") == key)
    .Remove();

UPDATE You almost did the job. What you missed is filtering elements by attribute value. Here is your code with filtering and removing selected elements:

xd.Element("Applications")
  .Element("myApp")
  .Elements("add")
  .Where(x => (string)x.Attribute("key") == key)
  .Remove();