How to remove an element from an xml using Xdocume

2019-04-19 23:24发布

问题:

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?

回答1:

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


回答2:

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