naren.katneni
naren.katneni

Reputation: 285

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

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?

Upvotes: 18

Views: 32914

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

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();

Upvotes: 36

L.B
L.B

Reputation: 116118

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();

Upvotes: 4

Related Questions