18

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?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
naren.katneni
  • 275
  • 1
  • 4
  • 10
  • Have you debugged the code? Do you know what .Element("myApp") is returning? Just looking for a bit more information about exactly what you are seeing happen. – Jr0 Dec 05 '12 at 20:18
  • Thanks for the suggestion. I understand .Element("myApp") returns the first element with the Name "myApp", correct? – naren.katneni Dec 05 '12 at 20:50

2 Answers2

36
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();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4
xd.Descendants("add")
    .First(a => a.Attribute("key").Value == "version")
    .Remove();

If you have tags other than myApp under Applications containing add, you may prefer a safer version

xd.Descendants("myApp").First()
    .Descendants("add")
    .Where(x => (string)x.Attribute("key") == "version")
    .Remove();

You can also use XPath (System.Xml.XPath)

string key="version";
xd.XPathSelectElement(String.Format("//myApp/add[@key='{0}']",key)).Remove();
L.B
  • 114,136
  • 19
  • 178
  • 224