当我们有多个具有相同名称但属性不同的元素时,如何使用Xdocument从xml中删除元素

nar*_*eni 12 c# xml linq linq-to-xml

我有一个xml文档,如下所示:

<Applications>
  <myApp>
    <add key="ErrorDestinationEventLog" value="EventLog" />
    <add key="version" value="5.0.0.0" />
    <add key="DebugMode_RUN" value="true" />
  </myApp>
</Applications>
Run Code Online (Sandbox Code Playgroud)

所有元素都具有相同的元素名称但属性不同.如何在C#中使用XDocument从此xml中删除一个特定元素及其属性?

xd.Element("Applications").Element("myApp").Element(xe.Name).RemoveAll();
Run Code Online (Sandbox Code Playgroud)

上述命令不起作用,因为所有元素都具有相同的名称.

除了它的名字之外,有没有办法识别元素?如果是这样,我如何使用它从XDocument中删除它?

Ser*_*kiy 24

string key = "version";
XDocument xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("add")
    .Where(x => (string)x.Attribute("key") == key)
    .Remove();
Run Code Online (Sandbox Code Playgroud)

更新你几乎完成了这项工作.您错过的是按属性值过滤元素.以下是过滤和删除所选元素的代码:

xd.Element("Applications")
  .Element("myApp")
  .Elements("add")
  .Where(x => (string)x.Attribute("key") == key)
  .Remove();
Run Code Online (Sandbox Code Playgroud)