Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
naren.katneni Avatar asked Dec 05 '12 19:12

naren.katneni


2 Answers

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();
like image 155
Sergey Berezovskiy Avatar answered Nov 07 '22 07:11

Sergey Berezovskiy


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();
like image 34
L.B Avatar answered Nov 07 '22 05:11

L.B